【发布时间】:2016-02-23 10:09:05
【问题描述】:
我可以使用以下代码获取给定接口的 IPv4 地址
int fd;
char ipv4[33];
char ifname[] = "eth0";
struct ifreq ifr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
snprintf(ipv4, 33, "%s", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
使用 C 获取给定接口的 IPv6 地址的最简单方法是什么?
*** 我正在发布我可以用来使其低于的代码..
int8_t find_device_ipv6(const char *ifname, char *ipv6, int8_t ipv6_size)
{
FILE *f;
int ret, scope, prefix;
unsigned char _ipv6[16];
char dname[IFNAMSIZ];
char address[INET6_ADDRSTRLEN];
char *scopestr;
f = fopen("/proc/net/if_inet6", "r");
if (f == NULL) {
return -1;
}
while (19 == fscanf(f,
" %2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx %*x %x %x %*x %s",
&_ipv6[0],
&_ipv6[1],
&_ipv6[2],
&_ipv6[3],
&_ipv6[4],
&_ipv6[5],
&_ipv6[6],
&_ipv6[7],
&_ipv6[8],
&_ipv6[9],
&_ipv6[10],
&_ipv6[11],
&_ipv6[12],
&_ipv6[13],
&_ipv6[14],
&_ipv6[15],
&prefix,
&scope,
dname)) {
if (strcmp(ifname, dname) != 0) {
continue;
}
if (inet_ntop(AF_INET6, _ipv6, address, sizeof(address)) == NULL) {
continue;
}
snprintf(ipv6, ipv6_size, "%s", address);
}
fclose(f);
return 0;
}
【问题讨论】:
-
这是特定于操作系统的。标准 C 中不存在套接字或网络接口。您可能需要添加
Posix或Linux标记 -
OpenWRT平台,基于Linux。
-
您真的需要特定接口的 v6 地址还是系统的主地址需要? (例如,用于传出连接的地址)