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

📄 ping.cpp

📁 此程序可以扫描多的IP和端口。另外可以多线程训话扫描
💻 CPP
字号:
// Ping.cpp: implementation of the CPing class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "JIEMIAN.h"
#include "Ping.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

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

CPing::CPing()
{
icmp_data = NULL;
	seq_no = 0;
	recvbuf = NULL;
	lpdest = NULL;
	datasize = DEF_PACKET_SIZE;
	
	m_hSocket = INVALID_SOCKET;
}

CPing::~CPing()
{

}
bool CPing::Ping(char *dest,int timeout)
{   
	//创建原始套接字,该套接字用于ICMP协议
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
    {
		AfxMessageBox("WSAStartup() failed");
        return false;
    }
	lpdest = dest;
	m_hSocket = WSASocket (AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0,
		WSA_FLAG_OVERLAPPED);
	
    if (m_hSocket == INVALID_SOCKET) 
    {
        AfxMessageBox("WSASocket() failed");
        return false;
    }
	
    
    //设置发送与接受超时值
    int bread = setsockopt(m_hSocket, SOL_SOCKET, SO_RCVTIMEO, 
		(char*)&timeout, sizeof(timeout));
    if(bread == SOCKET_ERROR) 
    {
        AfxMessageBox("setsockopt(SO_RCVTIMEO) failed");
        return false;
    }
    timeout = 1000;//超时值为1000
    bread = setsockopt(m_hSocket, SOL_SOCKET, SO_SNDTIMEO, 
		(char*)&timeout, sizeof(timeout));
    if (bread == SOCKET_ERROR) 
    {
        AfxMessageBox("setsockopt(SO_SNDTIMEO) failed");
        return false;
    }
	
	//指定目标地址信息
    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;
			// printf("m_addrDest.sin_addr = %s\n", inet_ntoa(m_addrDest.sin_addr));
        }
        else
        {
            AfxMessageBox("gethostbyname() failed");
            return false;
        }
    }        
	
    // 创建报文数据包,先分配内存,在调用FillCMPData填充IcmpHeader结构      
    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) 
    {
        AfxMessageBox("HeapAlloc() failed");
        return false;
    }
    memset(icmp_data,0,MAX_PACKET);
    FillICMPData(icmp_data,datasize);
    
    //开始发送/接受ICMP请求与应答
	static int nCount = 0;
    while(1) 
    {
        int        bwrote;
		
		//如果三次都能正确返回ICMP包则认为主机能够ping通
        if (nCount++ == 3) 
            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);
		//调用sendto()函数,向远程主机发送ICMP请求
        bwrote = sendto(m_hSocket, icmp_data, datasize, 0, 
			(struct sockaddr*)&m_addrDest, sizeof(m_addrDest));
		//出错处理
        if (bwrote == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAETIMEDOUT) 
            {
				// AfxMessageBox("timed out--Send");
                continue;
            }
            AfxMessageBox("sendto() failed");
            return false;
        }
		
		int fromlen = sizeof(m_addrFrom);
		//调用recvfrom()函数,接受远程主机的ICMP应答信息
        bread = recvfrom(m_hSocket, recvbuf, MAX_PACKET, 0, 
			(struct sockaddr*)&m_addrFrom, &fromlen);
		//超时出错处理(认为不能ping通)
        if (bread == SOCKET_ERROR)
        {
            if (WSAGetLastError() == WSAETIMEDOUT) 
            {
                //AfxMessageBox("timed out");
				return false;
                //continue;
            }
            AfxMessageBox("recvfrom() failed");
            return false;
        }
		//对接受的数据进行解析
		if (!DecodeICMPHeader(recvbuf, bread, &m_addrFrom))
			return false;
		
	}
	nCount = 0;
	return true;
}

void CPing::Cleanup()
{
	if (m_hSocket != INVALID_SOCKET) 
        closesocket(m_hSocket);
	
    HeapFree(GetProcessHeap(), 0, recvbuf);
    HeapFree(GetProcessHeap(), 0, icmp_data);
	
	m_hSocket = INVALID_SOCKET;
    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);
}


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

bool CPing::DecodeICMPHeader(char *buf, int bytes, SOCKADDR_IN *from)
{
	IpHeader       *iphdr = NULL;
    IcmpHeader     *icmphdr = NULL;
    unsigned short  iphdrlen;
	
    iphdr = (IpHeader *)buf;
	
    iphdrlen = iphdr->h_len * 4;
	
    if (bytes  < iphdrlen + ICMP_MIN) 
    {
     //   AfxMessageBox("Too few bytes");
		return false;
    }
    icmphdr = (IcmpHeader*)(buf + iphdrlen);
	
    if (icmphdr->i_type != ICMP_ECHOREPLY) 
    {
    //    AfxMessageBox("nonecho type");
        return false;
    }
    // Make sure this is an ICMP reply to something we sent!
    //
    if (icmphdr->i_id != (USHORT)GetCurrentProcessId()) 
    {
      //  AfxMessageBox("someone else's packet!\n");
        return false;
    }
    return true;
}

⌨️ 快捷键说明

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