获取IP地址的C代码

如何使用C代码获取本地计算机的IP地址?

如果有多个接口,那么我应该能够显示每个接口的IP地址。

注意:请勿在C代码中使用ifconfig之类的任何命令来检索IP地址。

 #include  #include  #include  #include  #include  #include  #include  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); } 

如果要枚举所有接口,请查看getifaddrs()函数 – 如果您使用的是Linux。

通过Michael Foukarakis的输入,我可以在同一台机器上显示各种接口的IP地址:

 #include  #include  #include  #include  #include  #include  #include  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(": %s \t 
%s\n", ifa->ifa_name, host); } } return 0; }

从“/ proc / net / dev”获取所有接口。 注意:它不能仅使用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); 

然后使用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. */ }