搜索文章:

首页  |  Java技术  |  Asp.net  |  Asp编程  |  VC/C++  |  Delphi  |  VB编程
上一篇:VPN技术详解 >>

微软ping程序源代码完整版

编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模块后都有我的详细注释和修改日志,希望能够对大家的学习有所帮助!!

/*本程序的主要源代码来自msdn网站, 笔者只是做了一些改进和注释! 另外需要注意的是在build之前,必须加入ws2_32.lib库文件,否则会提示"error lnk2001:"的错误!*/

/******************************************************************************\
version 1.1 修改记录:
<1> 解决了socket阻塞的问题,从而能够正确地处理超时的请求!
----------------------------------------------------------------------------------------------------
version 1.2 修改记录:
<1> 增加了由用户控制发送icmp包的数目的功能(即命令的第二个参数).
<2> 增加了对ping结果的统计功能.
\******************************************************************************/

#pragma pack(4)

#include
#include
#include

#define icmp_echo 8
#define icmp_echoreply 0

#define icmp_min 8 // minimum 8 byte icmp packet (just header)

/* the ip header */
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;
unsigned char proto; // protocol (tcp, udp etc)
unsigned short checksum; // ip checksum

unsigned int sourceip;
unsigned int destip;

}ipheader;

//
// icmp header
//
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 std header, but we reserve space for time */
ulong timestamp;
}icmpheader;

#define status_failed 0xffff
#define def_packet_size32
#define def_packet_number4/* 发送数据报的个数 */
#define max_packet 1024

#define xmalloc(s) heapalloc(getprocessheap(),heap_zero_memory,(s))
#define xfree(p) heapfree (getprocessheap(),0,(p))

void fill_icmp_data(char *, int);
ushort checksum(ushort *, int);
int decode_resp(char *,int ,struct sockaddr_in *);

void usage(char *progname){

fprintf(stderr,"usage:\n");
fprintf(stderr,"%s [number of packets] [data_size]\n",progname);
fprintf(stderr,"datasize can be up to 1kb\n");
exitprocess(status_failed);

}
int main(int argc, char **argv){

wsadata wsadata;
socket sockraw;
struct sockaddr_in dest,from;
struct hostent * hp;
int bread,datasize,times;
int fromlen = sizeof(from);
int timeout = 1000;
int statistic = 0;/* 用于统计结果 */
char *dest_ip;
char *icmp_data;
char *recvbuf;
unsigned int addr=0;
ushort seq_no = 0;

if (wsastartup(makeword(2,1),&wsadata) != 0){
fprintf(stderr,"wsastartup failed: %d\n",getlasterror());
exitprocess(status_failed);
}

if (argc <2 ) {
usage(argv[0]);
}
sockraw = wsasocket(af_inet,sock_raw,ipproto_icmp,null, 0,wsa_flag_overlapped);

//
//注:为了使用发送接收超时设置(即设置so_rcvtimeo, so_sndtimeo),
//必须将标志位设为wsa_flag_overlapped !
//

if (sockraw == invalid_socket) {
fprintf(stderr,"wsasocket() failed: %d\n",wsagetlasterror());
exitprocess(status_failed);
}
bread = setsockopt(sockraw,sol_socket,so_rcvtimeo,(char*)&timeout,
sizeof(timeout));
if(bread == socket_error) {
fprintf(stderr,"failed to set recv timeout: %d\n",wsagetlasterror());
exitprocess(status_failed);
}
timeout = 1000;
bread = setsockopt(sockraw,sol_socket,so_sndtimeo,(char*)&timeout,
sizeof(timeout));
if(bread == socket_error) {
fprintf(stderr,"failed to set send timeout: %d\n",wsagetlasterror());
exitprocess(status_failed);
}
memset(&dest,0,sizeof(dest));

hp = gethostbyname(argv[1]);

if (!hp){
addr = inet_addr(argv[1]);
}
if ((!hp) && (addr == inaddr_none) ) {
fprintf(stderr,"unable to resolve %s\n",argv[1]);
exitprocess(status_failed);
}

if (hp != null)
memcpy(&(dest.sin_addr),hp->h_addr,hp->h_length);
else
dest.sin_addr.s_addr = addr;

if (hp)
dest.sin_family = hp->h_addrtype;
else
dest.sin_family = af_inet;

dest_ip = inet_ntoa(dest.sin_addr);

//
//atoi函数原型是: int atoi( const char *string );
//the return value is 0 if the input cannot be converted to an integer !
//
if(argc>2)
{
times=atoi(argv[2]);
if(times == 0)
times=def_packet_number;
}
else
 times=def_packet_number;

if (argc >3)
{
datasize = atoi(argv[3]);
 if (datasize == 0)
 datasize = def_packet_size;
if (datasize >1024) /* 用户给出的数据包大小太大 */
{
fprintf(stderr,"warning : data_size is too large !\n");
datasize = def_packet_size;
}
}
else
 datasize = def_packet_size;

datasize += sizeof(icmpheader);
icmp_data = (char*)xmalloc(max_packet);
recvbuf = (char*)xmalloc(max_packet);

if (!icmp_data) {
fprintf(stderr,"heapalloc failed %d\n",getlasterror());
exitprocess(status_failed);
}


memset(icmp_data,0,max_packet);
fill_icmp_data(icmp_data,datasize);

//
//显示提示信息
//
fprintf(stdout,"\npinging %s ....\n\n",dest_ip);


for(int i=0;i{
int bwrote;

((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(sockraw,icmp_data,datasize,0,(struct sockaddr*)&dest,sizeof(dest));
if (bwrote == socket_error){
if (wsagetlasterror() == wsaetimedout) {
printf("request timed out.\n");
continue;
}
fprintf(stderr,"sendto failed: %d\n",wsagetlasterror());
exitprocess(status_failed);
}
if (bwrote < datasize ) {
fprintf(stdout,"wrote %d bytes\n",bwrote);
}
bread = recvfrom(sockraw,recvbuf,max_packet,0,(struct sockaddr*)&from,&fromlen);
if (bread == socket_error){
if (wsagetlasterror() == wsaetimedout) {
printf("request timed out.\n");
continue;
}
fprintf(stderr,"recvfrom failed: %d\n",wsagetlasterror());
exitprocess(status_failed);
}
if(!decode_resp(recvbuf,bread,&from))
statistic++; /* 成功接收的数目++ */
sleep(1000);

}

/*
display the statistic result
*/
fprintf(stdout,"\nping statistics for %s \n",dest_ip);
fprintf(stdout,"packets: sent = %d,received = %d, lost = %d (%2.0f%% loss)\n",times,
statistic,(times-statistic),(float)(times-statistic)/times*100);


wsacleanup();
return 0;

}
/*
the response is an ip packet. we must decode the ip header to locate
the icmp data
*/
int decode_resp(char *buf, int bytes,struct sockaddr_in *from) {

ipheader *iphdr;
icmpheader *icmphdr;
unsigned short iphdrlen;

iphdr = (ipheader *)buf;

iphdrlen = (iphdr->h_len) * 4 ; // number of 32-bit words *4 = 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) {
fprintf(stderr,"non-echo type %d recvd\n",icmphdr->i_type);
return 1;
}
if (icmphdr->i_id != (ushort)getcurrentprocessid()) {
fprintf(stderr,"someone else's packet!\n");
return 1;
}
printf("%d bytes from %s:",bytes, inet_ntoa(from->sin_addr));
printf(" icmp_seq = %d. ",icmphdr->i_seq);
printf(" time: %d ms ",gettickcount()-icmphdr->timestamp);
printf("\n");
return 0;

}


ushort 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);
}
/*
helper function to fill in various stuff in our icmp request.
*/
void fill_icmp_data(char * icmp_data, int datasize){

icmpheader *icmp_hdr;
char *datapart;

icmp_hdr = (icmpheader*)icmp_data;

icmp_hdr->i_type = 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);
//
// place some junk in the buffer.
//
memset(datapart,'e', datasize - sizeof(icmpheader));

}

/******************* 附: ping命令执行时显示的画面 ***************\
*c:\documents and settings\houzhijiang>ping 236.56.54.12 *
**
*pinging 236.56.54.12 with 32 bytes of data:*
**
*request timed out. *
*request timed out. *
*request timed out. *
*request timed out. *
**
*ping statistics for 236.56.54.12:*
* packets: sent = 4, received = 0, lost = 4 (100% loss),*
**
\*********************************************************/

/*********************************************************\
*c:\documents and settings\houzhijiang>ping 127.0.0.1*
* *
*pinging 127.0.0.1 with 32 bytes of data:*
* *
*reply from 127.0.0.1: bytes=32 time<1ms ttl=128*
*reply from 127.0.0.1: bytes=32 time<1ms ttl=128*
*reply from 127.0.0.1: bytes=32 time<1ms ttl=128*
*reply from 127.0.0.1: bytes=32 time<1ms ttl=128*
* *
*ping statistics for 127.0.0.1:*
* packets: sent = 4, received = 4, lost = 0 (0% loss),*
*approximate round trip times in milli-seconds: *
* minimum = 0ms, maximum = 0ms, average = 0ms*
**
\********************************************************/

()

相关文章:
© 2006   www.java-asp.net