如何使用C代码获取本地计算机的IP地址?
如果有多个接口,那么我应该能够显示每个接口的IP地址。
注意:请勿在C代码中使用 ifconfig 等任何命令来检索IP地址。
答案 0 :(得分:10)
#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);
}
如果要枚举所有接口,请查看getifaddrs()
函数 - 如果您使用的是Linux。
答案 1 :(得分:3)
使用Michael Foukarakis的输入,我可以在同一台机器上显示各种接口的IP地址:
#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;
}
答案 2 :(得分:-1)
从“/ 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. */
}