3 #include <sys/socket.h>
14 * Return the IP address for the given interface or "no IP" if the
15 * interface is up and running but hasn't got an IP address yet
18 const char *get_ip_addr(const char *interface) {
19 static char part[512];
21 socklen_t len = sizeof(struct sockaddr_in);
22 memset(part, 0, sizeof(part));
24 /* First check if the interface is running */
25 (void)strcpy(ifr.ifr_name, interface);
26 if (ioctl(general_socket, SIOCGIFFLAGS, &ifr) < 0 ||
27 !(ifr.ifr_flags & IFF_RUNNING))
30 /* Interface is up, get the IP address */
31 (void)strcpy(ifr.ifr_name, interface);
32 ifr.ifr_addr.sa_family = AF_INET;
33 if (ioctl(general_socket, SIOCGIFADDR, &ifr) < 0)
37 if ((ret = getnameinfo(&ifr.ifr_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
38 fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));