linux c ping 实现

用c语言实现的linux中的ping命令

 #include <stdio.h>
#include <signal.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#define PACKET_SIZE 4096
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 3
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd,datalen=;
int nsend=,nreceived=;
struct sockaddr_in dest_addr;
pid_t pid;
struct sockaddr_in from;
struct timeval tvrecv;
pthread_t tid;
void statistics();
unsigned short cal_chksum(unsigned short *addr,int len);
int pack(int pack_no);
void send_packet(void);
void recv_packet(void );
int unpack(char *buf,int len);
void tv_sub(struct timeval *out,struct timeval *in);
void statistics()
{ printf("\n--------------------PING statistics-------------------\n");
printf("%d packets transmitted, %d received , %%%d lost\n",nsend,nreceived,
(nsend-nreceived)/nsend*);
close(sockfd);
exit();
}
/*校验和算法*/
unsigned short cal_chksum(unsigned short *addr,int len)
{ int nleft=len;
int sum=;
unsigned short *w=addr;
unsigned short answer=; /*把ICMP报头二进制数据以2字节为单位累加起来*/
while(nleft>)
{ sum+=*w++;
nleft-=;
}
/*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/
if( nleft==)
{ *(unsigned char *)(&answer)=*(unsigned char *)w;
sum+=answer;
}
sum=(sum>>)+(sum&0xffff);
sum+=(sum>>);
answer=~sum;
return answer;
}
/*设置ICMP报头*/
int pack(int pack_no)
{ int i,packsize;
struct icmp *icmp;
struct timeval *tval;
icmp=(struct icmp*)sendpacket;
icmp->icmp_type=ICMP_ECHO;
icmp->icmp_code=;
icmp->icmp_cksum=;
icmp->icmp_seq=pack_no;
icmp->icmp_id=pid;
packsize=+datalen;
tval= (struct timeval *)icmp->icmp_data;
gettimeofday(tval,NULL); /*记录发送时间*/
icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize); /*校验算法*/
return packsize;
}
/*发送三个ICMP报文*/
void send_packet()
{ int packetsize;
nsend++;
packetsize=pack(nsend); /*设置ICMP报头*/
if( sendto(sockfd,sendpacket,packetsize,,(struct sockaddr *)&dest_addr,sizeof(dest_addr) )< )
{
perror("sendto error");
return;
}
alarm(); }
/*接收所有ICMP报文*/
void recv_packet(void )
{
//int send = *(int *) arg;
int n,fromlen;
extern int errno;
fromlen=sizeof(from);
while()
{ if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),, (struct sockaddr *)&from,&fromlen)) <)
{
if(errno==EINTR)
{
perror("recvfrom error");
}
continue; }
gettimeofday(&tvrecv,NULL); /*记录接收时间*/
unpack(recvpacket,n);
nreceived++;
}
}
/*剥去ICMP报头*/
int unpack(char *buf,int len)
{ int i,iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip=(struct ip *)buf;
iphdrlen=ip->ip_hl<<; /*求ip报头长度,即ip报头的长度标志乘4*/
icmp=(struct icmp *)(buf+iphdrlen); /*越过ip报头,指向ICMP报头*/
len-=iphdrlen; /*ICMP报头及ICMP数据报的总长度*/
if( len<) /*小于ICMP报头长度则不合理*/
{ printf("ICMP packets\'s length is less than 8\n");
return -;
}
/*确保所接收的是我所发的的ICMP的回应*/
if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) )
{ tvsend=(struct timeval *)icmp->icmp_data;
tv_sub(&tvrecv,tvsend); /*接收和发送的时间差*/
rtt=tvrecv.tv_sec*+tvrecv.tv_usec/; /*以毫秒为单位计算rtt*/
/*显示相关信息*/
printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n",
len,
inet_ntoa(from.sin_addr),
icmp->icmp_seq,
ip->ip_ttl,
rtt);
}
else return -;
}
main(int argc,char *argv[])
{ struct hostent *host;
struct protoent *protocol;
unsigned long inaddr=0l;
int waittime=MAX_WAIT_TIME;
int size=*;
if(argc<)
{ printf("usage:%s hostname/IP address\n",argv[]);
exit();
}
if( (protocol=getprotobyname("icmp") )==NULL)
{ perror("getprotobyname");
exit();
}
/*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/
if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<)
{ perror("socket error");
exit();
}
/* 回收root权限,设置当前用户权限*/
//setuid(getuid());
/*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的
的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/ setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) );
bzero(&dest_addr,sizeof(dest_addr));
dest_addr.sin_family=AF_INET;
/*判断是主机名还是ip地址*/
if( inaddr=inet_addr(argv[])==INADDR_NONE)
{ if((host=gethostbyname(argv[]) )==NULL) /*是主机名*/
{ perror("gethostbyname error");
exit();
}
memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length);
}
else /*是ip地址*/
memcpy( (char *)&dest_addr,(char *)&inaddr,host->h_length);
/*获取main的进程id,用于设置ICMP的标志符*/
pid=getpid();
printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[],
inet_ntoa(dest_addr.sin_addr),datalen); signal(SIGALRM,send_packet);
signal(SIGINT,statistics);
send_packet(); /*发送所有ICMP报文*/
//recv_packet(); /*接收所有ICMP报文*/
int ret = pthread_create(&tid, NULL, (void*)recv_packet, NULL);
if(ret != )
{
printf("Thread Create Error\n");
exit();
}
//statistics(SIGALRM); /*进行统计*/
pthread_join(tid, NULL);
return ;
}
/*两个timeval结构相减*/
void tv_sub(struct timeval *out,struct timeval *in)
{ if( (out->tv_usec-=in->tv_usec)<)
{ --out->tv_sec;
out->tv_usec+=;
}
out->tv_sec-=in->tv_sec;
}

涉及到的技术线程,信号量。

在使用线程的时候注意pthread_join的使用,该函数类似于waitpid 。由于不知道哪个进程先结束,如果主线程先结束了,那么有些变量多个线程都在使用,有可能由于主线程的结束使一些资源(该例子中的socket),致使其他线程无法使用。

su root

gcc ping.c -o ping -lpthread

./ping www.baidu.com

上一篇:Java创建线程的四种方式


下一篇:SharePoint 2013 文档库中PPT转换PDF