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

作者:侯志江     单位:天津大学软件学院       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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/576518.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ElasticSearch原理

3.1解析es的分布式架构 3.1.1分布式架构的透明隐藏特性 ElasticSearch是一个分布式系统&#xff0c; 隐藏了复杂的处理机制 分片机制:我们不用关心数据是按照什么机制分片的、最后放入到哪个分片中 分片的副本: 集群发现机制(cluster discovery):比如当前我们启动了一-个es进程…

实时重复文章识别——SimHash

一、背景介绍 在前边的文章中&#xff0c;我们采用的是用google的Doc2Vec模型来识别重复文章的&#xff0c;从线上运行的效果来看&#xff0c;它的准确率是比较高的。当然&#xff0c;这是建立在把所有的文章都当做训练数据来训练Doc2Vec模型的基础上的&#xff0c;它推断出一篇…

Duplicate entry...for key...

Duplicate entry...for key...的错误原因是主键的唯一值重复&#xff0c;在对数据库进行修改、插入操作时&#xff0c;一但主键的唯一值重复就会报此错误&#xff0c;有时在表中存在多个主键时&#xff0c;对表操作仍然报此错误&#xff0c;是因为对该表的索引造成的。例如一个…

深入理解simhash原理

一、LSH 介绍 LSH(Locality sensitive hashing)是局部敏感性hashing&#xff0c;它与传统的hash是不同的。传统hash的目的是希望得到O&#xff08;1&#xff09;的查找性能&#xff0c;将原始数据映射到相应的桶内。 LSH的基本思想是将空间中原始数据相邻的2个数据点通过映…

我的bolg,我的收获(MVC首次接触)

一&#xff1a;VO&#xff1a;定义变量和getter和getter方法。 二&#xff1a;DBC&#xff1a;DateBaseConnection 三&#xff1a;接口&#xff1a;记住接口首字母用I开头。并且查询时用FindXxx等等区别 四:Impl实现类&#xff1a; 五&#xff1a;代理模式&#xff0c;负责关闭…

IntelliJ IDEA tomcat配置

1&#xff0c;首先安装好 IntelliJ IDEA 开发工具 2&#xff0c;右上角这里有个 Edit Configurations 3,添加模板 选择本地安装的tomcat 和 选择jdk 4&#xff0c;添加tomcat 这里tomcat就安装好了

Think in Java之斐波那契数列

斐波纳契数列&#xff08;Fibonacci Sequence&#xff09;&#xff0c;又称黄金分割数列。 指的是这样一个数列&#xff1a;1、1、2、3、5、8、13、21、……这个数列从第三项开始&#xff0c;每一项都等于前两项之和。 在数学上&#xff0c;斐波纳契数列以如下被以递归的方法定…

(论文阅读笔记1)Collaborative Metric Learning(一)(WWW2017)

一、摘要 度量学习算法产生的距离度量捕获数据之间的重要关系。这里&#xff0c;我们将度量学习和协同过滤联系起来&#xff0c;提出了协同度量学习&#xff08;CML&#xff09;&#xff0c;它可以学习出一个共同的度量空间来编码用户偏好和user-user 和 item-item的相似度。 …

《论道HTML5》内容技术分享活动

HTML5小组的第12次活动&#xff0c;本期沙龙围绕5月出版的《论道HTML5》重点章节内容展开&#xff0c;由我和另外一位作者秀野堂主现场分享。欢迎大家参加&#xff0c;下面是活动的详细信息。活动介绍&#xff1a;时间&#xff1a;2012年04月21日 13:30-18:00地址&#xff1a;东…

基于SpringBoot实现一个可扩展的事件总线

基于SpringBoot实现一个可扩展的事件总线 前言 在日常开发中&#xff0c;我们经常会用到事件总线&#xff0c;SpringBoot通过事件多播器的形式为我们提供了一个事件总线&#xff0c;但是在开发中我们经常会用到其他的实现&#xff0c;比如Guava、Disruptor的。我们将基于Spri…

(论文阅读笔记1)Collaborative Metric Learning(二)(WWW2017)

三、协同度量学习 这一部分&#xff0c;我们讨论CML作为一种更自然的方法获得关联关系。CML的思路是这样的&#xff1a;我们在已知正例关系的user-item集合S上建立一个隐性反馈模型&#xff0c;并且学习user-item的距离作为他们的关系。学习到的距离使得S中的对更加紧密&#x…

处理sharepoint 列表中的 person or group类型字段

如果直接取列表项的值&#xff0c;person or group 类型字段会是 userid;#value 的样式&#xff0c;所以对此类型字段需转换成 spuser 处理 SPUser test GetSPUser(oItem, assocList.Fields.GetField("AssociateName"));if (user.Sid.Equals(test.Sid)){ ...}privat…

大数据技术之 Kafka (第 1 章 Kafka 概述)

第 1 章 Kafka 概述 1.1 定义 Kafka 是一个分布式的基于发布/订阅模式的消息队列&#xff08;Message Queue&#xff09;&#xff0c;主要应用于大数据实时处理领域。 1.2 消息队列 1.2.1 传统消息队列的应用场景 MQ传统应用场景之异步处理 使用消息队列的好处 1&a…

那些你无比崇拜的厉害人,是如何建构知识体系的

那些你无比崇拜的厉害人&#xff0c;是如何建构知识体系的&#xff1f; 2018-04-04 六合同风 文 | Lachel 高效思维达人&#xff0c;知识管理专家&#xff0c;深度思考践行者&#xff0c;领英、36氪特约作家 来源 | L先生说&#xff08;ID&#xff1a;lxianshengmiao&#x…

嵌入式成长轨迹25 【Linux应用编程强化】【Linux下的C编程 下】【实例:客户端/服务器端程序】...

给出一个客户/服务器程序开发的案例&#xff0c;实现从服务器状态的远程监视功能。同时&#xff0c;客户端采用图形界面来显示数据。这个案例涵盖了网络编程和GUI编程的相关知识&#xff0c;读者应该注意其中的结合点。具体内容包括&#xff1a; 服务器端程序设计 客户端程序设…

TODO L

要写的目录 最近一段时间&#xff0c;由于太忙&#xff08;根本就是懒&#xff09;停止了博客的更新&#xff0c;时间也快有一年了。停博的这段时间&#xff0c;在我身上是发生了太多太多事。关于技术博客&#xff0c;我将想写的主题暂列如下&#xff0c;后边慢慢补充。 1 si…

大数据技术之 Kafka (第 2 章 Kafka快速入门)

第 2 章 Kafka 快速入门 下载安装kafka集群 1.需要jdk 2.需要zookeeper&#xff0c;这个东西在最新版的Kafka中内置。 3.下载Kafka安装包 &#xff08;下载官网地址&#xff1a;Apache Kafka&#xff09; 一&#xff0c;下载Kafka安装包 二&#xff0c;Kafka安装包上传li…

使用ICSharpCode.TextEditor制作一个语法高亮显示的XML编辑器

本文转载&#xff1a;http://www.cnblogs.com/lefay/archive/2010/07/25/1784919.html转载于:https://www.cnblogs.com/51net/archive/2012/04/21/2462431.html

文因互联 CEO 鲍捷:确保搞砸人工智能项目的十种方法

文因互联 CEO 鲍捷&#xff1a;确保搞砸人工智能项目的十种方法 原文链接 原创&#xff1a; 鲍捷 文因互联 前天 做成一件事儿不容易&#xff0c;而坑恒在。 鲍捷博士于5月10日在将门创投的线上 talk 中盘点了人工智能项目的大坑小坑&#xff0c;选出了看上去非常反常识的十…