简体   繁体   中英

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

I have written a simple UDP server. Well, naturally I use recvfrom() function somewhere in it. 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() :

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

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):

Fix:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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