c++ - 原始 ICMP 套接字 : recvfrom() not recieving any data

标签 c++ windows sockets raw-sockets

以下代码是一个旨在发送 ICMP 回显请求并接收回复的程序。

/*
    Forgive my lack of error handling :)
*/
SOCKET ASOCKET = INVALID_SOCKET;
struct sockaddr saddr;
struct sockaddr_in *to = (struct sockaddr_in *) &saddr;
struct sockaddr_in from;
int fromsize = sizeof(from);
std::string ip = "[arbitrary ip address]";

struct ICMP {
    USHORT type;
    USHORT code;
    USHORT cksum;
    USHORT id;
    USHORT seq;
}*_ICMP;

char sendBuffer[sizeof(struct ICMP)];
char recvBuffer[256];

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

memset(&saddr, NULL, sizeof(saddr));
ASOCKET = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);

//  Configure timeout
DWORD timeoutmilsec = 3000;
setsockopt(ASOCKET, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeoutmilsec, sizeof(timeoutmilsec));

to->sin_family = AF_INET;
inet_pton(AF_INET, ip.c_str(), &(to->sin_addr));

_ICMP = new ICMP();

_ICMP->type = 8;
_ICMP->code = 0;
_ICMP->cksum = 0;
_ICMP->id = rand();
_ICMP->seq++;
// I have omitted my declaration of checksum() for simplicity
_ICMP->cksum = checksum((u_short *)_ICMP, sizeof(struct ICMP));

memcpy(sendBuffer, _ICMP, sizeof(struct ICMP));

if (sendto(ASOCKET, sendBuffer, sizeof(sendBuffer), NULL, (sockaddr *)&saddr, sizeof(saddr)) == SOCKET_ERROR)
{
    printf("sendto() failed with error: %u\n", WSAGetLastError());
    return false;
}

if (recvfrom(ASOCKET, recvBuffer, sizeof(recvBuffer), NULL, (sockaddr *)&from, &fromsize) == SOCKET_ERROR)
{
    if (WSAGetLastError() == TIMEOUTERROR)
    {
        printf("Timed out\n\n");
        return false;
    }

    printf("recvfrom() failed with error: %u\n", WSAGetLastError());
    return false;
}

我的问题是,我的 recvfrom() 调用没有收到任何数据并返回 TIMEOUTERROR (10060),尽管 ping 已得到回复(Wireshark 捕获)发送的请求和回复)。 sendto() 可以工作,但 recvfrom() 的行为很奇怪,我不知道问题是什么。

我发现有趣的是 recvfrom() 仅当网关告诉我主机无法访问时才会接收数据;如果主机可访问并且已响应 ping,则不会。

最佳答案

问题出在struct ICMP

ICMP 的

typecode应为unsigned char

ICMP header 应为 8 字节,但 struct ICMP 的大小为 10 字节。

所以应该改为:

struct ICMP {
    unsigned char type;
    unsigned char code;
    USHORT cksum;
    USHORT id;
    USHORT seq;
}*_ICMP;

关于c++ - 原始 ICMP 套接字 : recvfrom() not recieving any data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42195217/

相关文章:

windows - 在 Windows 命令提示符中列出所有可用命令的命令

c - 使用 mingw 套接字上的 fprintf

c++ - 如何解密加密文本?

c++ - QDbus:在同一路径上注册多个对象

windows - Qt安装程序卡住了

windows - 如何防止 WinDbg 附加到特定的子进程?

c++ - 在 C++ 中以微秒的分辨率测量时间?

c++ - 具有依赖于时钟时间的私有(private)成员的方法的 GTest

c++ - 在 C++ 中使用 connect() 时设置超时

multithreading - 线程可以共享同一个客户端套接字吗?