Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TCP recvfrom() doesn't store 'from'

I'm making a server program using TCP and I want to get the IP adress of the sender of the message I just received. Here's my code:

case FD_READ:
{    //Incoming data; get ready to receive
    char buffer[DEFAULT_BUFLEN];
    int bytes_received; 
    memset(buffer, '\0', sizeof(buffer));

    struct sockaddr_in recvIn;
    int recv_length = sizeof(struct sockaddr);

    memset((void *)&recvIn, '\0', recv_length);

    bytes_received = recvfrom(wParam, buffer, DEFAULT_BUFLEN, 0, (struct sockaddr *)&recvIn, &recv_length);
    cout << inet_ntoa(recvIn.sin_addr) << "\n";

    break;
}

So I'm using Windows messages to see if I should check for packets. Receiving data works, I can read it and everything. But the recvIn variable doesn't get altered by recvfrom. So when I do the cout << inet_ntoa(recvIn.sin_addr) << "\n" it writes "0.0.0.0". I've googled this problem and most other people that had this problem forgot to initialize the recv_length. But I'm pretty sure I did that correctly here. Can anyone see what I'm doing wrong? Or do I need to change something with the data that's being sent? Does the incoming data maybe not have the IP adress. Which is something I highly doubt, because I'm using TCP.

Thank you for you time, I hope I can get this solved!

like image 609
Maxim Schoemaker Avatar asked Dec 19 '25 00:12

Maxim Schoemaker


2 Answers

TCP is a connection-oriented protocol. from and fromlen are meant to be used with connectionless protocols, such as UDP. According to the documentation, recvfrom ignores from and fromlen for connection-oriented sockets.

like image 132
João Mendes Avatar answered Dec 20 '25 13:12

João Mendes


For a connected TCP socket, you should use getpeername() to obtain the address of the remote socket.

like image 21
Dave S Avatar answered Dec 20 '25 12:12

Dave S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!