win32 API 实现ping功能

#include "stdafx.h"
#include <winsock2.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#pragma comment(lib,"Ws2_32.lib")
#pragma comment(lib,"Iphlpapi.lib")

int _tmain(int argc, _TCHAR* argv[])
{
 // Declare and initialize variables
    int i;
    HANDLE hIcmpFile;
    unsigned long ipaddr = INADDR_NONE;
    DWORD dwRetVal = 0;
    char SendData[] = "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("192.168.0.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);
  printf("/t data = %s/n",pEchoReply->Data);
    }
    else {
        printf("/tIcmpSendEcho returned error: %ld/n", GetLastError() );//出错之后,必须马上调用这个函数才能出现返回错误。
        printf("/tCall to IcmpSendEcho failed./n");        return 1;
    }
 scanf("%d",&i);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值