gpt4 book ai didi

c - 为什么我在尝试接受连接时遇到 "Invalid argument"?

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

在接下来的代码中,当我尝试连接客户端时,服务器显示以下错误:

"invalid argument", I can't see the error.

if((l_sock=socket(AF_INET,SOCK_STREAM,0))!=-1)
{
struct sockaddr_in srv_dir;

srv_dir.sin_family=AF_INET;
srv_dir.sin_port=8500;
srv_dir.sin_addr.s_addr=INADDR_ANY;

if((bind(l_sock,(struct sockaddr *)&srv_dir,sizeof(struct sockaddr_in)))!=-1)
{
if(!(listen(l_sock,5)))
{
signal(SIGINT,cerraje);
int t_sock;
struct sockaddr_in cli_dir;
socklen_t tam;
time_t tstmp;
struct tm * res;
res=(struct tm *)malloc(sizeof(struct tm));

while(!key)
{
if((t_sock=accept(l_sock,(struct sockaddr *)&cli_dir,&tam))!=-1)
{
tstmp=time(&tstmp);
res=gmtime(&tstmp);
send(t_sock,res,sizeof(struct tm),0);
wr_hora(*res,cli_dir.sin_addr);
}
else
perror("Petición no atendida");//The error is printed here.

最佳答案

阅读 accept(2) 上的文档:

The addrlen argument is a value-result argument: it should initially contain the size of the structure pointed to by addr; on return it will contain the actual length (in bytes) of the address returned. When addr is NULL nothing is filled in.

因此,您需要使用 sizeof(cli_dir) 初始化传递给 accepttam 值。您很幸运,套接字库能够捕获您的错误,因为您传递的是未初始化的内存,这会导致未定义的行为。

关于c - 为什么我在尝试接受连接时遇到 "Invalid argument"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44058118/

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