以下代码是一个旨在发送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;
}

我的问题是,尽管ping 已回复(Wireshark捕获了请求并已发送答复),但我的recvfrom()调用未收到任何数据并返回TIMEOUTERROR(10060)。 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++ - RAW ICMP套接字: recvfrom() not recieving any data,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42195217/

10-11 22:43