我想在localhost上创建一个服务器,使用本地主机的IPv6映射IPv4地址,但我得到的是错误99.我不确定我在这里做错了什么:
#define IPv6_MAPPED_IPv4_LOCAL_ADDRESS "::FFFF:127.0.0.1" //localhost
#define PORT 12345
static int server()
{
int fd, v6only;
struct sockaddr_in6 addr6;
v6only = 0;
/* IPv6 TCP socket */
fd = socket(AF_INET6, SOCK_STREAM, 0);
if (fd == -1) {
fprintf(stderr, "Creating tcp socket failed \n");
return -1;
}
memset(&addr6, 0, sizeof(struct sockaddr_in6));
addr6.sin6_family = AF_INET6;
memcpy(addr6.sin6_addr.s6_addr, IPv6_MAPPED_IPv4_LOCAL_ADDRESS, sizeof(struct in6_addr));
addr6.sin6_port = htons(PORT);
addr6.sin6_scope_id = 0;
/* use setsockopt() to enable dual stack on the server */
if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)) < 0) {
fprintf(stderr, "Setting IPV6_V6ONLY to 0 failed error %s \n", strerror(errno));
close(fd);
return -1;
}
/* bind server socket to the address */
if (bind(fd, (struct sockaddr *)&addr6, sizeof(struct sockaddr_in6)) < 0) {
fprintf(stderr, "Binding socket failed error %s\n", strerror(errno));
close(fd);
return -1;
}
}
服务器失败,错误为Binding socket failed error Cannot assign requested address
答案 0 :(得分:2)
addr6.sin6_addr.s6_addr
不是字符串的地址,而是二进制格式。您需要使用inet_pton
将字符串转换为此二进制格式。
在
中inet_pton(AF_INET6, IPv6_MAPPED_IPv4_LOCAL_ADDRESS, &addr6.sin6_addr.s6_addr);