为什么我不能IPv6套接字绑定到一个LINKLOCAL地址 [英] why can't i bind ipv6 socket to a linklocal address
问题描述
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sock, length, fromlen, n;
struct sockaddr_in6 server;
struct sockaddr_in6 from;
int portNr = 5555;
char buf[1024];
length = sizeof (struct sockaddr_in6);
sock=socket(AF_INET6, SOCK_DGRAM, 0);
if (sock < 0) error("Opening socket");
bzero((char *)&server, length);
server.sin6_family=AF_INET6;
server.sin6_addr=in6addr_any;
server.sin6_port=htons(portNr);
inet_pton( AF_INET6, "fe80::21f:29ff:feed:2f7e", (void *)&server.sin6_addr.s6_addr);
//inet_pton( AF_INET6, "::1", (void *)&server.sin6_addr.s6_addr);
if (bind(sock,(struct sockaddr *)&server,length)<0)
error("binding");
fromlen = sizeof(struct sockaddr_in6);
while (1) {
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,&fromlen);
if (n < 0) error("recvfrom");
write(1,"Received a datagram: ",21);
write(1,buf,n);
n = sendto(sock,"Got your message\n",17,
0,(struct sockaddr *)&from,fromlen);
if (n < 0) error("sendto");
}
}
当我编译并运行上述code我:
when I compile and run the above code I got :
binding: Invalid argument
如果更改绑定 :: 1
并保留其他的事情在源$ C $ C不变,code
作品!所以你能告诉我有什么错我的code?先谢谢了。
and if change to bind the ::1
and leave other thing unchanged in the source code, the code
works! so could you tell me what's wrong with my code ? thanks in advance.
推荐答案
有关链路本地地址,你还需要指定与该地址相关联的网络接口......像这样的范围ID:
For link-local addresses, you also need to specify the scope ID of the network interface that is associated with the address... something like this:
server.sin6_scope_id = 5; /* or whatever the scope ID is for the network interface you want to communicate over */
您可以使用getifaddrs()来查找您的系统上提供的各种范围ID和网络接口它们对应的。
You can use getifaddrs() to find the various scope IDs available on your systems, and the network interfaces they correspond to.
(是的,这是一个痛苦...或者你也许可以追加)类似%EN0字符串的结尾传递给inet_pton(和inet_pton()可能做的工作,为你..我不知道,如果inet_pton()处理该语法或没有)
(Yes, it's a pain... alternatively you might be able to append something like "%en0" to the end of the string you pass to inet_pton(), and inet_pton() might do the work for you... I'm not sure if inet_pton() handles that syntax or not)
这篇关于为什么我不能IPv6套接字绑定到一个LINKLOCAL地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!