1 /**
2  * @file ifaddrs.c  Network interface code using getifaddrs().
3  *
4  * Copyright (C) 2010 Creytiv.com
5  */
6 #include <unistd.h>
7 #include <sys/socket.h>
8 #define __USE_MISC 1   /**< Use MISC code */
9 #include <net/if.h>
10 #include <ifaddrs.h>
11 #include <re_types.h>
12 #include <re_fmt.h>
13 #include <re_sa.h>
14 #include <re_net.h>
15 
16 
17 #define DEBUG_MODULE "ifaddrs"
18 #define DEBUG_LEVEL 5
19 #include <re_dbg.h>
20 
21 
22 /**
23  * Get a list of all network interfaces including name and IP address.
24  * Both IPv4 and IPv6 are supported.
25  *
26  * @param ifh Interface handler, called once per network interface.
27  * @param arg Handler argument.
28  *
29  * @return 0 if success, otherwise errorcode.
30  */
31 int net_getifaddrs(net_ifaddr_h *ifh, void *arg)
32 {
33 	struct ifaddrs *ifa, *ifp;
34 	int err;
35 
36 	if (!ifh)
37 		return EINVAL;
38 
39 	if (0 != getifaddrs(&ifa)) {
40 		err = errno;
41 		DEBUG_WARNING("getifaddrs: %m\n", err);
42 		return err;
43 	}
44 
45 	for (ifp = ifa; ifa; ifa = ifa->ifa_next) {
46 		struct sa sa;
47 
48 		DEBUG_INFO("ifaddr: %10s flags=%08x\n", ifa->ifa_name,
49 			   ifa->ifa_flags);
50 
51 		if (ifa->ifa_flags & IFF_UP) {
52 			err = sa_set_sa(&sa, ifa->ifa_addr);
53 			if (err)
54 				continue;
55 
56 			if (ifh(ifa->ifa_name, &sa, arg))
57 				break;
58 		}
59 	}
60 
61 	freeifaddrs(ifp);
62 
63 	return 0;
64 }
65