#include <stdio.h> #include <stdlib.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 get_dev_ip(char *dev, char ip[16]) { int sockfd; struct ifreq ifr; sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd == -1) { perror("socket() ERROR"); return -1; } ifr.ifr_addr.sa_family = AF_INET; strcpy(ifr.ifr_name, dev); if (ioctl(sockfd, SIOCGIFADDR, &ifr) == -1) { perror("ioctl(SIOCGIFADDR) ERROR"); return -1; } sprintf(ip, "%s", inet_ntoa(((struct sockaddr_in *)&(ifr.ifr_addr))->sin_addr)); close(sockfd); return 0; } int main(void) { char eth0_ip[16]; char eth1_ip[16]; get_dev_ip("eth0", eth0_ip); get_dev_ip("eth1", eth1_ip); printf("eth0 ip: %s\n", eth0_ip); printf("eth1 ip: %s\n", eth1_ip); return 0; }