`
gyht0808
  • 浏览: 115047 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Ping源代码

阅读更多
Ping1.h
// Ping1.h: interface for the CPing class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_PING1_H__E4EC8E17_BBE4_4C73_B589_29A1E9FC2D4C__INCLUDED_)
#define AFX_PING1_H__E4EC8E17_BBE4_4C73_B589_29A1E9FC2D4C__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#define IP_RECORD_ROUTE  0x7
#define DEF_PACKET_SIZE  32 
#define MAX_PACKET       1024      // Max ICMP packet size
#define MAX_IP_HDR_SIZE  60        // Max IP header size w/options
#define ICMP_ECHO        8
#define ICMP_ECHOREPLY   0
#define ICMP_MIN         8 // Minimum 8-byte ICMP packet (header)

#pragma comment(lib,"ws2_32.lib")   
typedef struct _iphdr 
{
    unsigned int   h_len:4;        // Length of the header
    unsigned int   version:4;      // Version of IP
    unsigned char  tos;            // Type of service
    unsigned short total_len;      // Total length of the packet
    unsigned short ident;          // Unique identifier
    unsigned short frag_and_flags; // Flags
    unsigned char  ttl;            // Time to live
    unsigned char  proto;          // Protocol (TCP, UDP etc)
    unsigned short checksum;       // IP checksum

    unsigned int   sourceIP;
    unsigned int   destIP;
} IpHeader;


typedef struct _icmphdr 
{
    BYTE   i_type;
    BYTE   i_code;                 // Type sub code
    USHORT i_cksum;
    USHORT i_id;
    USHORT i_seq;
    // This is not the standard header, but we reserve space for time
    ULONG  timestamp;
} IcmpHeader;

//
// IP option header - use with socket option IP_OPTIONS
//
typedef struct _ipoptionhdr
{
    unsigned char        code;        // Option type
    unsigned char        len;         // Length of option hdr
    unsigned char        ptr;         // Offset into options
    unsigned long        addr[9];     // List of IP addrs
} IpOptionHeader;


class CPing  
{
public:
	void usage(char* progname);
	void ValidateArgs(int argc, char** argv);
	void DecodeIPOptions(char *buf, int bytes);
	void Cleanup();
	void Ping(int timeout =1000);
	SOCKET m_hSocket;
	IpOptionHeader   m_ipopt;
	SOCKADDR_IN m_addrDest;
	SOCKADDR_IN m_addrFrom;
	char              *icmp_data;
    char              *recvbuf;
	 USHORT             seq_no ;
	 char *lpdest;
	int   datasize;
	BOOL m_bRecordRout;
	CPing();
	virtual ~CPing();

private:
	void DecodeICMPHeader(char *buf, int bytes, SOCKADDR_IN* from);
	USHORT checksum(USHORT *buffer, int size);
	void FillICMPData(char *icmp_data, int datasize);
};

#endif // !defined(AFX_PING1_H__E4EC8E17_BBE4_4C73_B589_29A1E9FC2D4C__INCLUDED_)

Ping1.cpp
// Ping1.cpp: implementation of the CPing class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Ping1.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CPing::CPing()
{
  icmp_data = NULL;
  seq_no = 0;
  recvbuf = NULL;
  m_bRecordRout = FALSE;
  lpdest = NULL;
  datasize = DEF_PACKET_SIZE;

  WSADATA wsaData;
  if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
        printf("WSAStartup() failed: %d\n", GetLastError());
        return ;
    }
  m_hSocket = INVALID_SOCKET;

}

CPing::~CPing()
{

}




  

void CPing::Ping(int timeout)
{   
	 m_hSocket = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,
                           WSA_FLAG_OVERLAPPED);

    if (m_hSocket == INVALID_SOCKET) 
    {
        printf("WSASocket() failed: %d\n", WSAGetLastError());
        return ;
    }

    if (m_bRecordRout)
    {
        // Setup the IP option header to go out on every ICMP packet
        //
        ZeroMemory(&m_ipopt, sizeof(m_ipopt));
        m_ipopt.code = IP_RECORD_ROUTE; // Record route option
        m_ipopt.ptr  = 4;               // Point to the first addr offset
        m_ipopt.len  = 39;              // Length of option header
  
        int ret = setsockopt(m_hSocket, IPPROTO_IP, IP_OPTIONS, 
            (char *)&m_ipopt, sizeof(m_ipopt));
        if (ret == SOCKET_ERROR)
        {
            printf("setsockopt(IP_OPTIONS) failed: %d\n", 
                WSAGetLastError());
        }
    }
    // Set the send/recv timeout values
    //
    int bread = setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO, 
                (char*)&timeout, sizeof(timeout));
    if(bread == SOCKET_ERROR) 
    {
        printf("setsockopt(SO_RCVTIMEO) failed: %d\n", 
            WSAGetLastError());
        return ;
    }
    timeout = 1000;
    bread = setsockopt(m_hSocket, SOL_SOCKET, SO_SNDTIMEO, 
                (char*)&timeout, sizeof(timeout));
    if (bread == SOCKET_ERROR) 
    {
        printf("setsockopt(SO_SNDTIMEO) failed: %d\n", 
            WSAGetLastError());
        return ;
    }
    memset(&m_addrDest, 0, sizeof(m_addrDest));
    //
    // Resolve the endpoint's name if necessary
    //
    m_addrDest.sin_family = AF_INET;
    if ((m_addrDest.sin_addr.s_addr = inet_addr(lpdest)) == INADDR_NONE)
    {   
		 struct hostent *hp = NULL;

        if ((hp = gethostbyname(lpdest)) != NULL)
        {
            memcpy(&(m_addrDest.sin_addr), hp->h_addr, hp->h_length);
            m_addrDest.sin_family = hp->h_addrtype;
            printf("m_addrDest.sin_addr = %s\n", inet_ntoa(m_addrDest.sin_addr));
        }
        else
        {
            printf("gethostbyname() failed: %d\n", 
                WSAGetLastError());
            return ;
        }
    }        

    // 
    // Create the ICMP packet
    //       
    datasize += sizeof(IcmpHeader);  

    icmp_data =(char*) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                  MAX_PACKET);
    recvbuf =(char*) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
                  MAX_PACKET);
    if (!icmp_data) 
    {
        printf("HeapAlloc() failed: %d\n", GetLastError());
        return ;
    }
    memset(icmp_data,0,MAX_PACKET);
    FillICMPData(icmp_data,datasize);
    //
    // Start sending/receiving ICMP packets
    //
    while(1) 
    {
        static int nCount = 0;
        int        bwrote;
                
        if (nCount++ == 4) 
            break;
                
        ((IcmpHeader*)icmp_data)->i_cksum = 0;
        ((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
        ((IcmpHeader*)icmp_data)->i_seq = seq_no++;
        ((IcmpHeader*)icmp_data)->i_cksum = 
            checksum((USHORT*)icmp_data, datasize);

        bwrote = sendto(m_hSocket, icmp_data, datasize, 0, 
                     (struct sockaddr*)&m_addrDest, sizeof(m_addrDest));
        if (bwrote == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAETIMEDOUT) 
            {
                printf("timed out\n");
                continue;
            }
            printf("sendto() failed: %d\n", WSAGetLastError());
            return ;
        }
        if (bwrote < datasize) 
        {
            printf("Wrote %d bytes\n", bwrote);
        }

		int fromlen = sizeof(m_addrFrom);
        bread = recvfrom(m_hSocket, recvbuf, MAX_PACKET, 0, 
                    (struct sockaddr*)&m_addrFrom, &fromlen);
        if (bread == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAETIMEDOUT) 
            {
                printf("timed out\n");
                continue;
            }
            printf("recvfrom() failed: %d\n", WSAGetLastError());
            return ;
        }
        DecodeICMPHeader(recvbuf, bread, &m_addrFrom);
        
    }
}

void CPing::Cleanup()
{
  if (m_hSocket != INVALID_SOCKET) 
        closesocket(m_hSocket);
    HeapFree(GetProcessHeap(), 0, recvbuf);
    HeapFree(GetProcessHeap(), 0, icmp_data);

    WSACleanup();
    return ;
}

void CPing::FillICMPData(char *icmp_data, int datasize)
{
   IcmpHeader *icmp_hdr = NULL;
    char       *datapart = NULL;

    icmp_hdr = (IcmpHeader*)icmp_data;
    icmp_hdr->i_type = ICMP_ECHO;        // Request an ICMP echo
    icmp_hdr->i_code = 0;
    icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
    icmp_hdr->i_cksum = 0;
    icmp_hdr->i_seq = 0;
  
    datapart = icmp_data + sizeof(IcmpHeader);
}

void CPing::DecodeIPOptions(char *buf, int bytes)
{
     IpOptionHeader *ipopt = NULL;
    IN_ADDR         inaddr;
    int             i;
    HOSTENT        *host = NULL;

    ipopt = (IpOptionHeader *)(buf + 20);

    printf("RR:   ");
    for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
    {
        inaddr.S_un.S_addr = ipopt->addr[i];
        if (i != 0)
            printf("      ");
        host = gethostbyaddr((char *)&inaddr.S_un.S_addr,
                    sizeof(inaddr.S_un.S_addr), AF_INET);
        if (host)
            printf("(%-15s) %s\n", inet_ntoa(inaddr), host->h_name);
        else
            printf("(%-15s)\n", inet_ntoa(inaddr));
    }
    return;
}

USHORT CPing::checksum(USHORT *buffer, int size)
{
   unsigned long cksum=0;

    while (size > 1) 
    {
        cksum += *buffer++;
        size -= sizeof(USHORT);
    }
    if (size) 
    {
        cksum += *(UCHAR*)buffer;
    }
    cksum = (cksum >> 16) + (cksum & 0xffff);
    cksum += (cksum >>16);
    return (USHORT)(~cksum);
}

void CPing::ValidateArgs(int argc,char** argv)
{
    int    i;
    
    for(i = 1; i < argc; i++)
    {
        if ((argv[i][0] == '-') || (argv[i][0] == '/'))
        {
            switch (tolower(argv[i][1]))
            {
                case 'r':        // Record route option
                    m_bRecordRout = TRUE;
                    break;
                default:
                    usage(argv[0]);
                    break;
            }
        }
        else if (isdigit(argv[i][0]))
            datasize = atoi(argv[i]);
        else
            lpdest = argv[i];
    }
}

void CPing::DecodeICMPHeader(char *buf, int bytes, SOCKADDR_IN *from)
{
   IpHeader       *iphdr = NULL;
    IcmpHeader     *icmphdr = NULL;
    unsigned short  iphdrlen;
    DWORD           tick;
    static   int    icmpcount = 0;

    iphdr = (IpHeader *)buf;
	// Number of 32-bit words * 4 = bytes
    iphdrlen = iphdr->h_len * 4;
    tick = GetTickCount();

    if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
        DecodeIPOptions(buf, bytes);

    if (bytes  < iphdrlen + ICMP_MIN) 
    {
        printf("Too few bytes from %s\n", 
            inet_ntoa(from->sin_addr));
    }
    icmphdr = (IcmpHeader*)(buf + iphdrlen);

    if (icmphdr->i_type != ICMP_ECHOREPLY) 
    {
        printf("nonecho type %d recvd\n", icmphdr->i_type);
        return;
    }
    // Make sure this is an ICMP reply to something we sent!
    //
    if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) 
    {
        printf("someone else's packet!\n");
        return ;
    }
    printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
    printf(" icmp_seq = %d. ", icmphdr->i_seq);
    printf(" time: %d ms", tick - icmphdr->timestamp);
    printf("\n");

    icmpcount++;
    return;
}

void CPing::usage(char *progname)
{
   printf("usage: ping -r <host> [data size]\n");
    printf("       -r           record route\n");
    printf("        host        remote machine to ping\n");
    printf("        datasize    can be up to 1KB\n");
    ExitProcess(-1);
}

Ping.cpp
// Ping.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Ping1.h"

// Description:
//    Print usage information
//

int main(int argc, char* argv[])
{   
	/*
	char* temp = "127.0.0.1";
	argv = &temp;*/

	if (argc != 2)
	{
		printf("You must specify who you want to ping on the command line\n");
		return -1;
	}
	
	CPing ping;
	ping.ValidateArgs(argc, argv);

	ping.Ping();
	Sleep(1000);
	printf("Ping end!\n");
	ping.Cleanup();
    getchar();
	return 0;
	
}
2
0
分享到:
评论

相关推荐

    VC++ Ping源代码

    首先,"VC++ Ping源代码"指的是使用Microsoft Visual C++编写的程序,用于实现对指定IP地址的ICMP(Internet Control Message Protocol)回显请求,即我们熟知的"Ping"功能。在Windows系统中,这个功能通常依赖于...

    Vc Ping 源代码

    "Vc Ping 源代码"是一个基于VC++编写的程序,它利用了Icmp(Internet Control Message Protocol)协议来实现网络上的"Ping"功能。Ping是网络诊断中常用的一个命令,用于测试网络连接的可达性和响应时间。在这个源...

    ping源代码程序

    ping源代码程序

    ping源代码

    ping源代码 linux下的

    ping 命令源代码

    在这个“ping命令源代码”压缩包中,我们很可能是得到了实现这一功能的原始代码,这对于理解ping工作原理和进行网络编程非常有帮助。 首先,让我们深入了解ping命令的工作原理。当用户在命令行中输入`ping ...

    c语言写的ping源代码

    用c写的ping源代码,看看绝对有益无害噢,

    ping 源代码 实验设计

    这个实验设计围绕着`ping`的源代码展开,旨在深入理解其工作原理,为网络编程和系统开发提供基础。下面我们将详细探讨`ping`命令的原理、实现以及在实验设计中的关键知识点。 首先,`ping`命令主要用于测试网络连接...

    microsoft-ping.rar_ping_ping 命令_ping 源代码

    在提供的"microsoft-ping.rar"压缩包中,包含了"ping"命令的源代码,这为我们深入理解其工作原理提供了宝贵资料。 "ping"命令的源代码虽然精简,但包含了网络通信的基础元素,如数据包的构建、发送和接收过程。源...

    linux 系统Ping 源代码

    在Linux内核2.6版本中,`ping`的源代码揭示了其工作原理和实现细节。这篇分析将深入探讨`ping`命令背后的编程概念和系统调用。 首先,`ping`的主要功能是发送ICMP回显请求(类型8,代码0)到目标主机,并等待接收...

    ping命令源代码

    描述中提到这是一份“很清晰完整的PING源代码”,适合对网络底层感兴趣的开发者进行深入研究。这表明该源代码不仅完整,而且易于理解,对于想要深入了解`ping`命令实现原理的人来说是非常有价值的资源。 #### 标签...

    ping的源代码

    终于找到了: 部分内容 &lt;br/&gt;ping的源代码 &lt;br/&gt;#pragma pack(4) #define WIN32_LEAN_AND_MEAN #include #include #include #define ICMP_ECHO 8 #define ICMP_ECHOREPLY 0 ...

    ping源代码,c语言实现

    这个`ping`程序的源代码是用C语言编写的,C语言是一种底层且高效的语言,非常适合编写这样的系统级工具。`ping`通过发送ICMP(Internet Control Message Protocol)回显请求数据包到目标主机,然后接收并分析回应,...

    网络PING源码

    通过上述分析,我们可以看到PING源代码不仅展示了网络通信的基本原理,还涉及了低层网络协议的实现细节,对于深入理解TCP/IP模型和网络编程具有重要的教育意义。对于学习者而言,通过阅读和理解这段源代码,可以更好...

    大名鼎鼎的Ping的源代码

    标题中的“大名鼎鼎的...此外,熟悉Ping源代码也有助于理解其他网络诊断工具的实现,比如Traceroute或Nslookup,这些工具同样基于低层网络协议进行操作。对于想要深入网络编程的开发者来说,这是一个宝贵的教育资源。

    Linux下Ping程序源代码

    自己写的Linux下的ping的简单原型,只有一个函数一个循环,几乎没有出错处理,不过结构清晰易懂,适合希望迅速理解ICMP实现Ping的人。

    ping 的源代码 网络应用

    // This sample illustrates how an ICMP ping app can be written // using the SOCK_RAW socket type and IPPROTO_ICMP protocol. // By creating a raw socket, the underlying layer does not change // the ...

    iputils ping源码

    iputils ping源码 traceroute源码 tftp源码

Global site tag (gtag.js) - Google Analytics