gpt4 book ai didi

C 套接字引发错误代码 22,EINVAL - 无效参数

转载 作者:太空狗 更新时间:2023-10-29 17:06:14 25 4
gpt4 key购买 nike

下面的示例代码用作服务器进程。但是当我添加行时

pid_t childpid;

下方

struct sockaddr_in servaddr, clientaddr;

在线失败

connectfd = accept(listenfd, (struct sockaddr *) &clientaddr, &clientaddrlen);

错误代码 22,EINVAL - 参数无效。我是 C 套接字的新手,我不明白这个问题,你能帮我解决这个问题吗?

谢谢。

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

extern int errno;

int main()
{
int clientaddrlen, listenfd, connectfd, bytes_rcvd, listen_queue_size=1;
short int port_no = 2000;
char buffer[1000];
struct sockaddr_in servaddr, clientaddr;

printf("Server running at port #%d\n", port_no);

// Create server socket.
if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
fprintf(stderr, "Cannot create server socket! errno=%d \n", errno);
exit(-1);
}
printf("Server socket created\n");

// Bind (attach) this process to the server socket.
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port_no);
bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
printf("Server socket is bound to port #%d\n", port_no);

// Turn 'listenfd' to a listening socket. Listen queue size is 1.
listen(listenfd,listen_queue_size);
printf("Server listening with a queue of size %d. \n", listen_queue_size);

// Wait for connection(s) from client(s).
while (1)
{
connectfd = accept(listenfd, (struct sockaddr *) &clientaddr, &clientaddrlen);
printf("A client has connected\n");
if (recv(connectfd, buffer, sizeof(buffer), 0 ) > 0)
printf("Received message: %s\n", buffer);
close(connectfd);
printf("Server closed connection to client\n");
}

close(listenfd);
return 0;
}

最佳答案

我没看到你在哪里初始化clientaddrlen。这是一个输入/输出参数。您必须告诉 accept() 地址的缓冲区有多大。

关于C 套接字引发错误代码 22,EINVAL - 无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886782/

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