gpt4 book ai didi

c - 绑定(bind): invalid argument when trying to bind AF_INET6 to INADDR_ANY (to localhost)

转载 作者:行者123 更新时间:2023-12-03 11:50:34 24 4
gpt4 key购买 nike

据我所知,IPv6环回是::1。所以当我尝试这个时:

//includes of all needed headers in one place
#include <include.h>

#define BACKLOG 10

int main(int argc, char const *argv[])
{
if (argc != 2)
{
die("Usage: %s <port>\n", argv[0]);
}
int port = atoi(argv[1]);
int numOfClient = 0;

int sockfd = socket(AF_INET6, SOCK_STREAM, 0);
struct sockaddr_in servaddr;

servaddr.sin_family = AF_INET6;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(port);

if (bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("bind");
}
else
{
printf("[+]bind\n");
}
if (listen(sockfd, BACKLOG) < 0)
{
perror("listen");
}
else
{
printf("[+]listening\n");
}
while (1)
{
int client_sockfd = accept(sockfd, NULL, NULL);
time_t now = time(NULL);
char *time_fmt = ctime(&now);
numOfClient++;

printf("client %d requested for time at %s\n", numOfClient, time_fmt);
if (write(client_sockfd, time_fmt, strlen(time_fmt) + 1) < 0)
{
die("died: write to client_sockfd\n");
}
}
return 0;
}

并尝试将其运行为:

$ # run with random port 4444
$ ./server6 4444
bind: Invalid argument
[+]listening

IF_INET 套接字没有问题,但 IF_INET6 似乎存在某种问题。它可能是什么?

最佳答案

您使用了错误的 sockaddr 结构类型。对于 IPv6,您需要使用 struct sockaddr_in6

struct sockaddr_in6 servaddr = { .sin6_family = AF_INET6, 
.sin6_addr = IN6ADDR_ANY_INIT,
.sin6_port = htons(port));

或者:

struct sockaddr_in6 servaddr = {0};

servaddr.sin6_family = AF_INET6;
servaddr.sin6_addr = in6addr_any;
servaddr.sin6_port = htons(port);

关于c - 绑定(bind): invalid argument when trying to bind AF_INET6 to INADDR_ANY (to localhost),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65495739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com