Paweł Hajdan
Paweł Hajdan

Reputation: 18542

How to produce struct addrinfo from struct sockaddr?

I have a struct sockaddr and need to make a struct addrinfo (specifically that, because that's what some other API wants). The IP address may be IPv4 or IPv6. What's the best way to handle that?

Upvotes: 3

Views: 5942

Answers (1)

ephemient
ephemient

Reputation: 204668

From man 3 getaddrinfo,

struct addrinfo {
    int              ai_flags;
    int              ai_family;
    int              ai_socktype;
    int              ai_protocol;
    size_t           ai_addrlen;
    struct sockaddr *ai_addr;
    char            *ai_canonname;
    struct addrinfo *ai_next;
};

A struct addrinfo contains more information than just a struct sockaddr does. Given a struct sockaddr_in, you can have some of this information (.ai_family = AF_INET, .ai_addrlen = sizeof(struct sockaddr_in)). Whether this is sufficient depends on what the other API is looking for.

Upvotes: 5

Related Questions