我想通了.....其实我没有,这个博客是真正帮助我的博客。我非常感谢他的建议。
http://valileo-valilei.blogspot.in/2010/09/getting-link-local-addres-from.html
这是一个实现:(我在这里提供代码,因为它可以帮助许多可能陷入类似情况的其他人)
代码:
#include "sys/types.h"
#include "ifaddrs.h"
#include <arpa/inet.h>
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int get_link_local_addr(char* if_name, int if_name_length,
struct sockaddr_in6 *ip) {
struct ifaddrs *ifaddr, *ifa;
int ret = -2;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
ret = -1;
freeifaddrs(ifaddr);
return ret;
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family != AF_INET6) continue;
if (strncmp(ifa->ifa_name, if_name, if_name_length)) continue;
struct sockaddr_in6 *current_addr =
(struct sockaddr_in6 *) ifa->ifa_addr;
if (!IN6_IS_ADDR_LINKLOCAL(&(current_addr->sin6_addr))) continue;
memcpy(ip, current_addr, sizeof(*current_addr));
ret = 0;
}
freeifaddrs(ifaddr);
return ret;
}
int main() {
struct sockaddr_in6 *sa=(struct sockaddr_in6 *)malloc(40);
char *src,dst[INET6_ADDRSTRLEN];
get_link_local_addr("wlan0",5,sa);
inet_ntop(AF_INET6, &(sa->sin6_addr), dst, INET6_ADDRSTRLEN);
printf("Link Layer Address is : %s\n",dst);
return 0;
}
输出:
Link Layer Address is : fe80::d2df:9aff:fe56:917d
在命令行上进行交叉检查:
$ ifconfig wlan0
wlan0
Link encap:Ethernet HWaddr d0:df:9a:56:91:7d
inet addr:172.31.9.171 Bcast:172.31.255.255 Mask:255.255.0.0
inet6 addr: 2001:df0:92:0:d2df:9aff:fe56:917d/64 Scope:Global
inet6 addr: fe80::d2df:9aff:fe56:917d/64 Scope:Link
inet6 addr: 2001:df0:92:0:50df:d286:a281:e6c0/64 Scope:Global
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:217235 errors:0 dropped:0 overruns:0 frame:0
TX packets:21173 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:31550379 (31.5 MB) TX bytes:4062945 (4.0 MB)