windows的ping发icmp的系统api

用windows的原生api做ping的测试程序,收藏一下

#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#include <stdio.h>

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

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


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

其中char SendData[32] = "Data Buffer";为icmp报文内容,icmp无端口概念,为ip层负载报文.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值