icmpscanning.cpp

// icmpscanning.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "winsock2.h"
#pragma comment(lib,"ws2_32.lib")
typedef struct lpHeader
{
unsigned char Version_HLen;//首部长度 ,ip 版本号
unsigned char TOS; //服务类型tos
unsigned short Length;//总长度
unsigned short Ident;//标示
unsigned short Flags_Offset;//标志位
unsigned char TTL; //生存时间 ttl
unsigned char Protocol;//协议类型
unsigned short Checksum;//ip首部校验和
unsigned int SourceAddr;//源ip地址
unsigned int DestinationAddr;//目的ip地址
}Ip_Header;
typedef struct IcmpHeader
{
BYTE Type;//8位类型
BYTE Code;//8位代码
USHORT Checksum;//16位校验和
USHORT ID;//16位识别号
USHORT Sequence;//16喂 报文序列号
}Icmp_Header;
//计算机校验和
USHORT checksum(USHORT *buff,int size)
{
unsigned long cksum=0;
while(size>1)
{
cksum+=*buff++;
size-=sizeof(USHORT);
}
if(size){
cksum+=*(UCHAR*)(buff);
}
cksum=(cksum>>16)+(cksum&0xffff);
cksum+=(cksum>>16);
return (USHORT)(~cksum);
}
//主函数
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
sockaddr_in DestAddr;
Ip_Header *ip;
Icmp_Header *icmp;
//发送icmp的数据
Icmp_Header *SendIcmp;
//设置超时
int Timeout=1000;
char DestIpAddr[100]="127.0.0.1";
//icmp的内容
char IcmpBuffer[8]="";
SOCKET IcmpSocket;
char RecvBuffer[1024];
sockaddr_in addr;
int Len=sizeof(addr);
int Result;
WSAStartup(MAKEWORD(2,2),&wsaData);
IcmpSocket=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
setsockopt(IcmpSocket,SOL_SOCKET,SO_RCVTIMEO,(char*)&Timeout,sizeof(Timeout));
memset(&DestAddr,0,sizeof(DestAddr));
DestAddr.sin_addr.s_addr=inet_addr(DestIpAddr);
DestAddr.sin_port=htons(0);
DestAddr.sin_family=AF_INET;
//填充icmp数据内容
SendIcmp=(Icmp_Header*)IcmpBuffer;
SendIcmp->Type=8;
SendIcmp->Code=0;
SendIcmp->ID=(USHORT)GetCurrentProcessId();
SendIcmp->Sequence=htons(1);
SendIcmp->Checksum=0;
SendIcmp->Checksum=checksum((USHORT*)IcmpBuffer,sizeof(IcmpBuffer));
//发送
sendto(IcmpSocket,IcmpBuffer,sizeof(IcmpBuffer),0,(SOCKADDR*)&DestAddr,sizeof(DestAddr));
recvfrom(IcmpSocket,RecvBuffer,1024,0,(sockaddr*)&addr,&Len);
ip=(Ip_Header*)RecvBuffer;
if((ip->SourceAddr==inet_addr(DestIpAddr))&&(ip->Protocol==IPPROTO_ICMP))
{
icmp=(Icmp_Header*)(RecvBuffer+sizeof(Ip_Header));
if(icmp->Type!=0)
{
printf("type error %d",icmp->Type);
return 0;

}
if(icmp->ID!=GetCurrentProcessId())
{
printf("id error %d\n",icmp->ID);
return 0;
}
else if((icmp->Type==0)&&(icmp->ID==GetCurrentProcessId())){
printf("Host%s is up\n",DestIpAddr);

}

}
closesocket(IcmpSocket);
WSACleanup();
getchar();

 

return 0;
}

 

posted @ 2013-05-23 14:13  herizai  阅读(175)  评论(0编辑  收藏  举报