使用c访问链接本地地址

时间:2013-01-21 10:21:55

标签: c sockets networking network-programming

我正在使用C。

构建的IPv6网络应用程序

现在根据我的要求,我需要用系统的链接本地地址填充我的数据包的默认地址。

glibc中是否有任何函数/库用于此目的。

我知道我可以使用system命令执行此操作,并运行可以从系统访问ifcfg-eth0的脚本,但我想这是不可行的。

我是所有这些套接字的新手,所以请原谅我是否遗漏了一些微不足道的东西。

修改:

OS:linux

这实际上是一个使用原始C套接字编程构建的开源实现sendip。现在,我正在修改它。根据我的要求。

http://snad.ncsl.nist.gov/ipv6/sendip.html

2 个答案:

答案 0 :(得分:2)

我想通了...... 实际上我没有,这个博客实际上帮助了我。 我很感谢他的建议。

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)

答案 1 :(得分:0)

如果你有一个IPv6应用程序,那么你有一个IPv6 API(套接字或其他东西)。

此API应具有获取系统链接本地地址的功能。

小心多宿主。