检测局域网IP在线

ICMP(Internet Control Message Protocol)Internet控制报文协议。它是TCP/IP协议簇的一个子协议,用于在IP主机、路由器之间传递控制消息。控制消息是指网络通不通、主机是否可达、路由是否可用等网络本身的消息。这些控制消息虽然并不传输用户数据,但是对于用户数据的传递起着重要的作用。

通过发送ICMP报文,根据返回值,判断ip在线。

#include <winsock2.h>

#include <iphlpapi.h>

#include <icmpapi.h>

#include <stdio.h>

#pragma comment(lib, "iphlpapi.lib")

#pragma comment(lib, "ws2_32.lib")

int main(int argc, char** argv) {

// Declare and initialize variables

HANDLE hIcmpFile;

unsigned long ipaddr = INADDR_NONE;

DWORD dwRetVal = 0;

char SendData[32] = "Data Buffer";

LPVOID ReplyBuffer = NULL;

DWORD ReplySize = 0;

// Validate the parameters

if (argc != 2) {

printf("usage: %s IP address\n", argv[0]);

return 1;

}

ipaddr = inet_addr(argv[1]);

if (ipaddr == INADDR_NONE) {

printf("usage: %s IP address\n", argv[0]);

return 1;

}

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;

}

while (true)

{

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", argv[1]);

if (dwRetVal > 1) {

printf("\tReceived %ld icmp message responses\n", dwRetVal);

printf("\tInformation from the first response:\n");

}

else {

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);//pEchoReply->Status = 0 时 ip存在

printf("\t Roundtrip time = %ld milliseconds\n",

pEchoReply->RoundTripTime);

}

else {

printf("\tCall to IcmpSendEcho failed.\n");

printf("\tIcmpSendEcho returned error: %ld\n", GetLastError());

//ip离线

//return 1;

}

//休眠两秒

::Sleep(2000);

}

return 0;

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

跑过那座山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值