Finding all IPv4 addresses associated with INADDR_ANY (?)

Chuck Swiger cswiger at mac.com
Mon Feb 23 22:49:06 PST 2004


Ronald F. Guilmette wrote:
> Given a socket which has been properly created, opened, and then bound
> to some port and the special INADDR_ANY ``wildcard'' address, I need
> to be able to them programatically find all of the IPv4 addresses that
> the socket was just bound to.

Try something like the following:

     struct ifaddrs *if_ptr, *ifap;

     if (getifaddrs(&ifap) == -1) {
         fatal(strerror(errno));
             /*NOTREACHED*/
     }

         /* iterate over the list of interfaces on the machine */
     for (if_ptr = ifap; if_ptr; if_ptr = if_ptr->ifa_next) {
         switch (if_ptr->ifa_addr->sa_family) {
           case AF_INET:
                 /* check that the interface is UP before we try to use it */
             flags = if_ptr->ifa_flags;
             if (!(flags & IFF_UP)) break;
	        /* do something here using if_ptr->ifa_addr */

           case AF_INET6:
                 /* do something else for IPv6... */
         }
     }

...although be sure to call ntohl() on the address to get things in the local 
byte-ordering...

-- 
-Chuck



More information about the freebsd-net mailing list