Wednesday, November 26, 2014

Programmatically getting the IP address of an interface

Here's a quick and simple example of how to programatically get the IP address of a given network interface.
/*
 * gcc getip.c -lsocket -lnsl -o getip
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stropts.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/sockio.h>

int
main(int argc, char **argv)
{
        struct sockaddr_in *ipaddr;
        struct ifreq if_idx;
        int fd;

        if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
                perror("Failed to open socket.\n");
                return (1);
        }

        memset(&if_idx, 0, sizeof(struct ifreq));
        (void) strlcpy(if_idx.ifr_name, "eth0", IFNAMSIZ-1);

        if (ioctl(fd, SIOCGIFINDEX, &if_idx) < 0) {
                perror("Failed to get interface index.\n");
                return (2);
        }

        if (ioctl(fd, SIOCGIFADDR, &if_idx) < 0) {
                perror("Failed to get interface address.\n");
                return (3);
        }

        ipaddr = (struct sockaddr_in*)&if_idx.ifr_addr;
 

        (void) printf("IP address for %s: %s\n", if_idx.ifr_name,
            inet_ntoa(ipaddr->sin_addr));

        return (0);
}

The output will be something like:
$ ./getip
IP address for eth0: 192.168.10.33

No comments:

Post a Comment