简体   繁体   English

Linux c ++ recvfrom()更改(销毁)[socket]文件描述符

[英]Linux c++ recvfrom() changes (destroys) the [socket] file descriptor

I have written a simple UDP server. 我已经编写了一个简单的UDP服务器。 Well, naturally I use recvfrom() function somewhere in it. 好吧,我自然会在其中的某个地方使用recvfrom()函数。 I have searched the net for it, and found that it is caused by the buffer overflow. 我在网上搜索了它,发现它是由缓冲区溢出引起的。 Is this true? 这是真的? But I can't figure why my code fails and throws the same error, here is the part associated with recvfrom() : 但是我不知道为什么我的代码会失败并引发相同的错误,这是与recvfrom()相关的部分:

char messageFromClient[1024] = {0};
returnStatus = recvfrom(udpSocket, &messageFromClient, strlen(messageFromClient), 0, (struct sockaddr*)&udpSocket,
                                &addrlen);

The file descriptor before invocation of recvfrom() is 3 but when I call it, it changes to -187301886 调用recvfrom()之前的文件描述符为3但是当我调用它时,它变为-187301886

Your code fails because you specify 0 receive buffer size and you pass the socket file descriptor as the peer address argument (which overwrites its value): 您的代码失败,因为您指定了0的接收缓冲区大小,并且将套接字文件描述符作为对等地址参数传递(覆盖了它的值):

Fix: 固定:

char messageFromClient[1024];
sockaddr_in addr;
socklen_t addrlen = sizeof addr;
ssize_t received = recvfrom(udpSocket, messageFromClient, sizeof messageFromClient, 0, (sockaddr*)&addr, &addrlen);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM