C code to get IP address

How do I get the IP address of the local computer using the C code?

If there are multiple interfaces, I should be able to display the IP address of each interface.

NOTE. Do not use any commands to get the IP address as the ifconfig code .

+2


source to share


3 answers


With Michael Foukarakis inputs, I can show the IP address for different interfaces on one machine:



#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        family = ifa->ifa_addr->sa_family;

        if (family == AF_INET) {
            s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
                                           host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("<Interface>: %s \t <Address> %s\n", ifa->ifa_name, host);
        }
    }
    return 0;
}

      

+3


source


#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>

int main()
{
    int fd;
    struct ifreq ifr;

    fd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;

    snprintf(ifr.ifr_name, IFNAMSIZ, "eth0");

    ioctl(fd, SIOCGIFADDR, &ifr);

    /* and more importantly */
    printf("%s\n", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

    close(fd);
}

      



If you want to list all interfaces, take a look at the function getifaddrs()

- if you are on Linux.

+10


source


Find out all interfaces from the "/ proc / net / dev" section. Note: it cannot use all interfaces with just ioctl.

#define PROC_NETDEV "/proc/net/dev"

fp = fopen(PROC_NETDEV, "r");
while (NULL != fgets(buf, sizeof buf, fp)) {
    s = strchr(buf, ':');
    *s = '\0';
    s = buf;

    // Filter all space ' ' here
    got one interface name here, continue for others
}
fclose(fp);

      

Then get the address using ioctl ():

struct ifreq ifr;
struct ifreq ifr_copy;
struct sockaddr_in *sin;

for each interface name {
    strncpy(ifr.ifr_name, ifi->name, sizeof(ifr.ifr_name) - 1);
    ifr_copy = ifr;
    ioctl(fd, SIOCGIFFLAGS, &ifr_copy);
    ifi->flags = ifr_copy.ifr_flags;
    ioctl(fd, SIOCGIFADDR, &ifr_copy);
    sin = (struct sockaddr_in*)&ifr_copy.ifr_addr;
    ifi->addr = allocating address memory here
    bzero(ifi->addr, sizeof *ifi->addr);
    *(struct sockaddr_in*)ifi->addr = *sin;

    /* Here also you could get netmask and hwaddr. */
}

      

-1


source







All Articles