gpt4 book ai didi

c - 单工通话 : accept: Invalid argument error with simple socket program

转载 作者:行者123 更新时间:2023-11-30 16:57:30 27 4
gpt4 key购买 nike

我通常不会用 C 语言写任何东西,所以请原谅我完全缺乏经验。我正在尝试教科书上的代码,但它给了我一个错误。我编译了客户端和服务器可执行文件。我运行服务器 ./server 和客户端 ./client localhost。每当我运行客户端时,包含服务器的终端都会显示错误 simplex-talk:accept: Invalid argument。我在某处读到,该参数可能是“值结果参数”。我不知道这意味着什么或它如何应用于此。这是代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#
#define SERVER_PORT 20169
#define MAX_PENDING 5
#define MAX_LINE 256
int
main()
{
struct sockaddr_in sin;
char buf[MAX_LINE];
socklen_t len;
int s, new_s;
/* build address data structure */
memset((char *)&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);
/* setup passive open */
if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
perror("simplex-talk: socket");
exit(1);
}
if ((bind(s, (struct sockaddr *)&sin, sizeof(sin))) < 0) {
perror("simplex-talk: bind");
exit(1);
}
listen(s, MAX_PENDING);
/* wait for connection, then receive and print text */
while(1) {
if ((new_s = accept(s, (struct sockaddr *)&sin, &len)) < 0) {
perror("simplex-talk: accept");
exit(1);
}
while (len = recv(new_s, buf, sizeof(buf), 0))
fputs(buf, stdout);
close(new_s);
}
}

最佳答案

您必须将len初始化为sizeof(sin)。否则(man 2 接受),

EINVAL Socket is not listening for connections, or addrlen is invalid (e.g., is negative).

关于c - 单工通话 : accept: Invalid argument error with simple socket program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475417/

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