⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ping.h

📁 这是一个经典的端口扫描的源程序
💻 H
字号:

//-------------------------------------------------------------------------------
//  Ping Class v1.0 Source Code for Visual C++ 6.0                         
//                                                                               
//     -->> Only I can free to use, modify, recompile!!!  Open it for me                                                                           
//  Author:    Mr.Plunix                                                        
//  HomePage:  NULL    
//  qq technologe group :   7234396                                                        
//  Release:   10/2/2005                                                        
//  Reference: NULL                                                           
//-------------------------------------------------------------------------------

#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment (lib,"ws2_32.lib")

#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)

class CPing  
{
public:
	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;

	void SetConfigure(char * host,int size=32,int Num=4);
	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;
	int PingNumber;
	BOOL m_bRecordRout;
	char msg[4096];
	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);
};

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

	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
	{
		return ;
	}
	m_hSocket = INVALID_SOCKET;

}

CPing::~CPing()
{
	if(lpdest)
		delete []lpdest;
}

  

void CPing::Ping(int timeout)
{   
	wsprintf(msg,"Ping %s\r\n",lpdest);
	m_hSocket = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,WSA_FLAG_OVERLAPPED);
    if (m_hSocket == INVALID_SOCKET) 
    {
        return ;
    }

    if (m_bRecordRout)
    {
        ZeroMemory(&m_ipopt, sizeof(m_ipopt));
        m_ipopt.code = IP_RECORD_ROUTE; 
        m_ipopt.ptr  = 4; 
        m_ipopt.len  = 39;
  
        int ret = setsockopt(m_hSocket, IPPROTO_IP, IP_OPTIONS, 
            (char *)&m_ipopt, sizeof(m_ipopt));
    }

    int bread = setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO, 
                (char*)&timeout, sizeof(timeout));
    if(bread == SOCKET_ERROR) 
    {
        return;
    }
    timeout = 1000;
    bread = setsockopt(m_hSocket, SOL_SOCKET, SO_SNDTIMEO, 
                (char*)&timeout, sizeof(timeout));
    if (bread == SOCKET_ERROR) 
    {
        return ;
    }
    memset(&m_addrDest, 0, sizeof(m_addrDest));
    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;
        }
        else
        {
            printf("gethostbyname() failed: %d\n", 
            WSAGetLastError());
            return ;
        }
    }              
    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) 
    {
        return ;
    }
    memset(icmp_data,0,MAX_PACKET);
    FillICMPData(icmp_data,datasize);
	int nCount=0;
    while(1) 
    {
        int        bwrote;    
        if (nCount++ == PingNumber)
            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) 
            {
				strcat(msg,"Timed out ! \r\n");
                continue;
            }
            return ;
        }
        if (bwrote < datasize) 
        {
			printf("Wrote %d bytes \r\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) 
            {
				strcat(msg,"Timed out !\r\n");
                continue;
            }
            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);

    for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
    {
        inaddr.S_un.S_addr = ipopt->addr[i];
        host = gethostbyaddr((char *)&inaddr.S_un.S_addr,
                    sizeof(inaddr.S_un.S_addr), AF_INET);
        if (host)
		{
			printf("(%-15s) %s \r\n", inet_ntoa(inaddr), host->h_name);
		}
        else
		{
			printf("(%-15s)\r\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::SetConfigure(char * host,int size,int Num)
{
	if(lpdest)
	{
		delete[] lpdest;
		lpdest=NULL;
	}
	PingNumber = Num;
    m_bRecordRout = FALSE;
    datasize = size;
    lpdest = new char [strlen(host)+1];
	strcpy(lpdest,host);
}

void CPing::DecodeICMPHeader(char *buf, int bytes, SOCKADDR_IN *from)
{
	char buff[1024];
    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) 
    {
		wsprintf(buff,"Too few bytes from %s \r\n",inet_ntoa(from->sin_addr));
		strcat(msg,buff);
	}	
    icmphdr = (IcmpHeader*)(buf + iphdrlen);

    if (icmphdr->i_type != ICMP_ECHOREPLY) 
    {
		wsprintf(buff,"nonecho type %d recvd \r\n", icmphdr->i_type);
        strcat(msg,buff);
		return;
    }
    // Make sure this is an ICMP reply to something we sent!
    //
    if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) 
    {
		wsprintf(buff,"someone else's packet! \r\n");
        strcat(msg,buff);
		return ;
    }

	wsprintf(buff,"%d bytes from %s: \r\n icmp_seq = %d. \r\n time: %d ms \r\n", bytes, inet_ntoa(from->sin_addr), icmphdr->i_seq,tick - icmphdr->timestamp);
	strcat(msg,buff);
	icmpcount++;
    return;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -