TCP recvfrom() doesn't store 'from'

2020-02-15 06:29发布

问题:

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!

回答1:

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.



回答2:

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