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