作者:侯志江     单位:天津大学软件学院       E-mail :tjuhzjemail@yahoo.com.cn   日期:2005年1月1日    
内容简介: 编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模块后都有我的详细注释和修改日志,希望能够对大家的学习有所帮助!!

/* 本程序的主要源代码来自MSDN网站, 笔者只是做了一些改进和注释! 另外需要注意的是在Build之前,必须加入ws2_32.lib库文件,否则会提示"error LNK2001:"的错误!*/
Version 1.1 修改记录:
     <1> 解决了socket阻塞的问题,从而能够正确地处理超时的请求!
     <2> 增加了由用户控制发送ICMP包的数目的功能(即命令的第二个参数)
     <3> 增加了对ping结果的统计功能.

#pragma pack(4)
#include   "winsock2.h"
#include   "stdlib.h"
#include   "stdio.h"
#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                                       *
*                                                                                                                         *
\**************************************************************/

转载于:https://www.cnblogs.com/spinsoft/archive/2012/04/07/2435728.html

微软ping程序源代码完整版(附详细的注释)相关推荐

  1. 微软ping程序源代码完整版

    微软ping程序源代码完整版 编写自己的一个ping程序,可以说是许多人迈出网络编程的第一步吧!!这个ping程序的源代码经过我的修改和调试,基本上可以取代windows中自带的ping程序. 各个模 ...

  2. ASCII码表 0-255完整版 附详细注释

    信息在计算机上是用二进制表示的,这种表示法让人理解就很困难.因此计算机上都配有输入和输出设备,这些设备的主要目的就是,以一种人类可阅读的形式将信息在这些设备上显示出来供人阅读理解.为保证人类和设备,设 ...

  3. Android课程表App完整版(附详细代码)

    实验目的 传统的纸质课程表容易丢失.损坏和不容易增删改,而随着越来越多的学生使用手机,这时课程表App可以解决这个问题,课程表App提供丰富的功能来对课程进行增删改查,采用数据库存储已不易损坏.本次课 ...

  4. QT界面免费版开源图片转文字工具程序完整版附源码

    QT界面免费版开源图片转文字工具程序完整版附源码 需求源码的朋友请留言 操作步骤如下:

  5. WEB学习路线2020完整版+附视频教程

    WEB学习路线2020完整版+附视频教程,适合初学者的最新WEB前端学习路线汇总! 在当下来说web前端开发工程师可谓是高福利.高薪水的职业了.所以现在学习web前端开发的技术人员也是日益增多了,但是 ...

  6. 通用(任何android机型)Root教程(完整版!附砖机自救方法)转自安卓网

    通用(任何android机型)Root教程(完整版!附砖机自救方法)转自安卓网 2012年01月02日 一台android终端(可能是手机.可能是平板,也可能是其它),很多功能是要取得Root权限后才 ...

  7. 宿舍管理程序c语言,学生宿舍管理软件C语言源代码完整版

    <学生宿舍管理软件C语言源代码完整版>由会员分享,可在线阅读,更多相关<学生宿舍管理软件C语言源代码完整版(8页珍藏版)>请在人人文库网上搜索. 1.源程序代码:#includ ...

  8. python课本答案上海交大第五章_高等数学课后习题答案上海交大版完整版非常详细_.pdf...

    高等数学课后习题答案上海交大版完整版非常详细_ 一诺整理 一诺整理 一一诺诺整整理理 高等数学 高等数学 课后习题答案 课后习题答案 (上海交大版) (上海交大版) ((上上海海交交大大版版)) /w ...

  9. php退款,php实现小程序退款完整版

    本文主要和大家分享php实现小程序退款完整版,功能前提:1. 使用 wx php sdk (小程序支付完整版) , 2. 配置证书时使用绝对路径希望能帮助到大家. 1. 上代码:/** * 退款 * ...

最新文章

  1. Python持续点火,跟进还是观望?
  2. Python之几种常用模块
  3. 什么是java构造函数_什么是java构造函数
  4. bzoj 2865 字符串识别——后缀数组
  5. Qt 5.9.1 连 MYSQL 5.7数据库
  6. sqlserver存储过程学习
  7. 在Linux操作系统下修改IP、DNS和路由配置
  8. 上传文件到云服务器一般用什么软件?
  9. HDLBits学习笔记——移位寄存器
  10. shopex手机版之触屏版,html5版,ShopEx手机触屏版V3.0重磅发布!优化用户界面,增强用户体验...
  11. 基于Java毕业设计在线装机报价系统源码+系统+mysql+lw文档+部署软件
  12. R语言Circos图可视化
  13. SQL面试题练习记录
  14. 字节跳动将双月OKR调整为季度;马斯克批OpenAI违背初心:被微软控制,只顾赚钱;苹果上新348元省电保护膜|极客头条...
  15. 优雅地从浏览器打开本地应用
  16. 我的青春恋爱物语果然有问题。完-OP分析
  17. 【新星计划·第三季】一篇关于学习算法和写博客的心得和经验
  18. Linux终端下后台运行程序被Stopped的原因以及解决
  19. VScode受难记 - 0
  20. QQ聊天记录快速迁移

热门文章

  1. mysql timestamp排序_对多个表进行排序MYSQL TimeStamp
  2. mysql 主从一致性_mysql 主从一致性保证
  3. # 解析bt文件_磁力链接和BT种子使用方法
  4. php写入文本乱码,如何解决PHP用fwrite写入文件中文乱码的问题
  5. MySQL 分组查询
  6. C语言数理逻辑题目,数学逻辑推理题整理,看看你能答对多少
  7. python爬虫能秒杀么_面试题之用python爬取并夕夕不同时段秒杀商品信息
  8. 数学建模学习笔记(十一)——预测模型
  9. dnn神经网络 缺点_抄近路神经网络如何因找捷径而犯错
  10. Python 小白从零开始 PyQt5 项目实战(8)汇总篇(完整例程)