TCP recvfrom() doesn't store 'from'

拈花ヽ惹草 提交于 2019-11-28 11:36:58

问题


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.



来源:https://stackoverflow.com/questions/12873484/tcp-recvfrom-doesnt-store-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!