我编写了一个解析地址或主机名的程序,然后尝试以listen(2)
模式绑定到该地址。由于某些奇怪的原因,我无法使用IPv6地址,程序在调用bind(2)
后失败并显示“无效参数”。使用IPv4,一切正常,我希望它能够工作,名称得到解决,地址只需转换为二进制格式。
来源
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <netdb.h>
#include <unistd.h>
static int
resolve_addr (const char *hostname, const char *service, int family, struct addrinfo **result)
{
struct addrinfo addr_hint;
memset (&addr_hint, 0, sizeof (struct addrinfo));
addr_hint.ai_socktype = SOCK_STREAM;
addr_hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG;
addr_hint.ai_family = family;
return getaddrinfo (hostname, service, &addr_hint, result);
}
int
main (int argc, char *argv[])
{
struct addrinfo *addr;
int rval, sock, opt_val;
rval = resolve_addr (argv[1], argv[2], AF_UNSPEC, &addr);
if ( rval != 0 ){
fprintf (stderr, "%s\n", gai_strerror (rval));
return 1;
}
sock = socket (addr->ai_family, addr->ai_socktype | SOCK_NONBLOCK, addr->ai_protocol);
if ( sock == -1 ){
fprintf (stderr, "error socket: %s\n", strerror (errno));
return 1;
}
if ( setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof (opt_val)) == -1 ){
fprintf (stderr, "error setsockopt: %s\n", strerror (errno));
return 1;
}
if ( bind (sock, (struct sockaddr*) addr->ai_addr, sizeof (struct sockaddr)) == -1 ){
fprintf (stderr, "error bind: %s\n", strerror (errno));
return 1;
}
if ( listen (sock, 32) == -1 ){
fprintf (stderr, "error listen: %s\n", strerror (errno));
return 1;
}
sleep (120);
freeaddrinfo (addr);
close (sock);
return 0;
}
用法
./test_bind localhost 8888 # works
./test_bind 0.0.0.0 8888 # works
./test_bind 127.0.0.1 8888 # works
./test_bind :: 8888 # does not work: Invalid argument
./test_bind ::1 8888 # does not work: Invalid argument
旁注
我使用netcat来查明我的系统是否有问题,但以下命令有效:
ncat -l :: 8888
可以在netstat中看到:
tcp6 0 0 :::8888 :::* LISTEN
答案 0 :(得分:2)
我更新了我的代码,IPv4和IPv6都被解析并绑定成功。问题出现在SQL> @f:\testa.txt
函数的第三个参数中,它是从结构大小计算地址的大小,而不是使用来自bind(2)
结果的值。
我换了一行:
getaddrinfo
使用:
if ( bind (sock, (struct sockaddr*) addr->ai_addr, sizeof (struct sockaddr)) == -1 ){
完整来源
if ( bind (sock, (struct sockaddr*) addr->ai_addr, addr->ai_addrlen) == -1 ){