上一篇:VPN技术详解 >>
微软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_size32
#define def_packet_number4/* 发送数据报的个数 */
#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*
**
\********************************************************/
()
下一篇:在xp和2003下察看端口对应的进程 >>
相关文章:
- · 利用SQLEXEC突破网络妙管免费上网
- · webshell下的一次得到终端账号和密码的尝试
- · 通过试验探索 Access 2000/XP 数据库的最佳 NTFS 权限设置
- · 简单更改W2K的Telnet端口
- · 电子邮件头解析
- · VMware还是微软?虚拟机的选择权就在你手中
- · asp中获取安全的参数
- · Google还可以这样用
- · Smail堆溢出漏洞允许远程攻击者获得Root权限
- · Linux下软件的安装与卸载
- · 学习设置端口映射
- · 收藏经典:windows消息大全
- · 一行代码崩溃IE
- · 脚本安全和利用
- · 亲手打造一个QQ恶作剧程序
- · CCIE:年薪翻了两倍
- · Linux认证基本知识介绍
- · 思科认证考生问答集
- · 微软认证考试的几种形式
- · 利用SSH从外网安全地访问PIX防火墙
- · 多网段环境下的Windows文件夹共享解决
- · 防火墙中使用Telnet、FTP、RealAudio
- · 网络经典命令行-网络安全工作者必杀技
- · Java 程序编码规范
- · FTP 鸡肉制作
- · 安全程序员必读书籍清单
- · 编辑web.config,保证ASP.NET的安全
- · 修复ADSL的Firmware之手记
- · Microsoft平台下的find在网络管理中的妙用
- · 利用组策略对象(GPOs)防止匿名登录
- · 删除系统顽固文件的十二招技巧
- · DoS攻击隐身于合法指令中 难以完全阻绝
- · 我能躲到哪里去?—无线定位技术
- · Windows“安全模式”的五项用途
- · ECHO命令的超详细使用
- · php注入专题
- · 对IPv6在NGI核心层和接入层部署的思考
- · IDS(入侵检测系统)术语
