Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 352
Paweł Hajdan Avatar asked Dec 13 '25 12:12

Paweł Hajdan


1 Answers

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.

like image 195
ephemient Avatar answered Dec 16 '25 09:12

ephemient



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!