TCP recvfrom()不存储“from” [英] TCP recvfrom() doesn't store 'from'

查看:326
本文介绍了TCP recvfrom()不存储“from”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TCP的服务器程序,我想获得刚刚收到的消息的发件人的IP地址。这是我的代码:

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



因此我使用Windows消息来查看是否应该检查数据包。接收数据工作,我可以读它和一切。但是recvIn变量不会被recvfrom改变。所以当我做cout< inet_ntoa(recvIn.sin_addr)<< \\\
它写入0.0.0.0。我已经google了这个问题,大多数有这个问题的人忘记初始化recv_length。但我很确定我在这里正确。任何人都可以看到我做错了什么?或者,我需要更改与正在发送的数据的东西吗?传入的数据可能没有IP地址。这是我非常怀疑,因为我使用TCP。

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!

推荐答案

TCP是面向连接的协议。 fromlen 意味着与无连接协议(如UDP)一起使用。根据文档 recvfrom 忽略来自 fromlen 套接字。

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.

这篇关于TCP recvfrom()不存储“from”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆