Icmp子网地址请求

时间:2014-11-13 18:48:08

标签: c++ icmp subnet

我正在尝试了解如何使用ICMP获取子网地址。在Wikipedia(其他来源)中,有一个消息示例,但我能找到的所有消息都与此消息无关。

尝试使用IcmpSendEcho(来自msdn example),但在我看来,它只执行ping功能,如果我错了就纠正我。

你能给我一些代码示例(c / c ++),还是链接?

编辑:

我使用的代码:

int __cdecl main()  {

// Declare and initialize variables

HANDLE hIcmpFile;
unsigned long ipaddr = INADDR_NONE;
DWORD dwRetVal = 0;
char SendData[12] = "Data Buffer";
LPVOID ReplyBuffer = NULL;
DWORD ReplySize = 0;
ipaddr = inet_addr("217.71.130.248");
hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE) {
    printf("\tUnable to open handle.\n");
    printf("IcmpCreatefile returned error: %ld\n", GetLastError());
    return 1;
}

ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
ReplyBuffer = (VOID*)malloc(ReplySize);
if (ReplyBuffer == NULL) {
    printf("\tUnable to allocate memory\n");
    return 1;
}

dwRetVal = IcmpSendEcho(hIcmpFile, ipaddr, SendData, sizeof(SendData),
    NULL, ReplyBuffer, ReplySize, 1000);
if (dwRetVal != 0) {
    PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
    struct in_addr ReplyAddr;
    ReplyAddr.S_un.S_addr = pEchoReply->Address;
    printf("\tSent icmp message to %s\n", "217.71.130.248");
    printf("\tReceived %ld icmp message response\n", dwRetVal);
    printf("\tInformation from this response:\n");

    printf("\t  Received from %s\n", inet_ntoa(ReplyAddr));
    printf("\t  Status = %ld\n",
        pEchoReply->Status);
    printf("\t  Roundtrip time = %ld milliseconds\n",
        pEchoReply->RoundTripTime);
}
else {
    printf("\tCall to IcmpSendEcho failed.\n");
    printf("\tIcmpSendEcho returned error: %ld\n", GetLastError());
    return 1;
}
return 0;

}

我从知识产权中得到答案,这很有效。但是我需要得到子网地址而且我被困在它身上

1 个答案:

答案 0 :(得分:0)

ECHO(又名ping)是一种特定类型的ICMP请求。 ICMP支持其他类型的消息,但IcmpSendEcho()只能发送ECHO个请求并接收ECHO个回复,因此其名称。因此,您无法使用它向路由器发送ADDRESS MASK请求以获取子网地址。

Microsoft没有用于发送通用ICMP请求的API。您必须使用标准套接字API(Windows上的WinSock)来创建类型为SOCK_RAW且协议为IPPROTO_ICMP的套接字(因为ICMP在IP之上运行但与TCP /分开) UDP),然后您可以手动构建和发送自己的ICMP请求,然后读取并解析ICMP回复。请注意,SOCK_RAW在大多数平台上都需要管理员权限,包括Windows。

话虽这么说,需要求助于ICMP来获取您机器的子网地址。操作系统已经知道它,并且有特定于操作系统的API可用于获取该信息,例如Windows上的GetAdaptersInfo()GetAdaptersAddresses()以及POSIX系统上的getifaddrs()

相关问题