1

I have a code which listed interfaces on a device and looked for an interface of a given name and type:

ifaddrs * ifAddrs = nullptr;
getifaddrs(&ifAddrs);
for (ifaddrs * it = ifAddrs ; it != nullptr ; it = it->ifa_next)
{
    if ((it->ifa_addr->sa_family == AF_INET) && (it->ifa_name == someInterfaceName))
    {
        // do stuff
    }
}

Now I'd like to add IPv6 support and so I modified the code like this (added af variable):

ifaddrs * ifAddrs = nullptr;
getifaddrs(&ifAddrs);
int af = ipv6Code ? AF_INET : AF_INET6;
for (ifaddrs * it = ifAddrs ; it != nullptr ; it = it->ifa_next)
{
    if ((it->ifa_addr->sa_family == af) && (it->ifa_name == someInterfaceName))
    {
        // do stuff
    }
}

But I don't know if it's correct. Namely, if it->ifa_addr->sa_family can ever be AF_INET6 or if it's always AF_INET to describe an internet connection (regardless of IPv4 vs IPv6)? I found for instance this page: https://www.tutorialspoint.com/unix_sockets/socket_structures.htm which only lists AF_INET but then again this page: how to get IPV6 interface address using getifaddr() function uses AF_INET6. So which one is it?

Community
  • 1
  • 1
NPS
  • 6,003
  • 11
  • 53
  • 90
  • You should consider the age of the articles you find. IPv6 has been kind of ignored a while back, so some tutorials don't mention this really. While an answer from 2015 probably seems more recent I would say. In case of doubt look in the header file which values are defined. – Hayt Oct 26 '16 at 11:29
  • Yes, I realize the articles might be out of date. That's why I'm asking experts. As for the header - there are plenty of `#define`s but that doesn't prove or disprove anything, they aren't directly related to the `sa_family` variable (or actually it's another macro). – NPS Oct 26 '16 at 11:41
  • usually they are defined close to each other. – Hayt Oct 26 '16 at 11:42

0 Answers0