我能夠用下面的代碼獲取IP版本6採用C
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));
什麼是獲得一個給定的接口的IPv6地址,用C最簡單的方式來獲得一個給定的接口的IPv4地址?
***我張貼的代碼,我可以用它來使之低於..
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」標記 –
它基於Linux,位於OpenWRT平臺上。 – BlueBird
也許重複http://stackoverflow.com/questions/20743709/get-ipv6-addresses-in-linux-using-ioctl –