ping命令的实现机制(包括:socket,icmp,信号等,已经通过调试,直接编译运行)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

本文实现了简单的ping命令,已经通过调试,只需编译,就可以运行了;本文加了不少注释,希望对一些想了解ping实现机制的同志有所帮助;
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <arpa/inet.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>
#include <sys/time.h>
#define PACKET_SIZE 4096
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd;
int datalen = 8;
int nsend = 0, nreceived = 0;
struct sockaddr_in dest_addr;
struct sockaddr_in from;
struct timeval tvrecv;
struct timeval tvstart;
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);
unsigned short cal_chksum(unsigned short *addr,int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
sum += *(unsigned char *)w;
printf("sum = %x\n", sum);
}
sum = (sum>>16) + (sum&0xffff);
sum += (sum>>16);
answer =~ sum;
return answer;
}
/*设置ICMP报头*/
int pack(int pack_no)
{
int packsize;
struct icmp *icmp;
struct timeval *tval;
icmp = (struct icmp*)sendpacket;
icmp->icmp_type = ICMP_ECHO;
icmp->icmp_code = 0;
icmp->icmp_cksum = 0;
icmp->icmp_seq = pack_no;
icmp->icmp_id = htons((unsigned short)getpid());
packsize = 8 + datalen;
printf("send size:%d\n", strlen(icmp->icmp_data));
tval = (struct timeval *)icmp->icmp_data;
gettimeofday(tval, NULL); /*记录发送时间*/
icmp->icmp_cksum = cal_chksum((unsigned short *)icmp,packsize); /*校验算法*/
return packsize;
}
void send_packet(void )
{
int packetsize;
nsend++;
packetsize = pack(nsend);
if (sendto(sockfd, sendpacket, packetsize, 0,(struct sockaddr *)&dest_addr, sizeof(struct sockaddr_in)) < 0)
{
printf("sendto error\n\r");
return;
}
}
void recv_packet(void )
{
int n;
socklen_t fromlen;
extern int errno;
struct timeval time1 ={0};
struct timeval time2 ={0};
char k = 0;
fromlen = sizeof(from);
gettimeofday(&time1, NULL);
while(1)
{
if ((n = recvfrom(sockfd, (void *)recvpacket, sizeof(recvpacket), 0,(struct sockaddr *)&from, &fromlen)) < 0)
{
if (errno == EINTR)
{
printf("errno == EINTR\n\r");
}
}
if (unpack(recvpacket, n) == 1)
{
nreceived++;
k = 1;
break;
}
gettimeofday(&time2, NULL);
if(1 < (_sec - _sec) )/*超时1秒*/
{
break;
}
}
if(0 == k)
{
printf("Host Unreachable\n\r");
}
return;
}
/*剥去ICMP报头*/
int unpack(char *buf,int len)
{
int iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip = (struct ip *)buf;
iphdrlen = ip->ip_hl<<2; /* ip_hl is the words of ip header*/
icmp = (struct icmp *)(buf+iphdrlen); /*越过ip报头,指向ICMP报头*/
len -= iphdrlen; /*ICMP报头及ICMP数据报的总长度*/
if (len < 8) /*小于ICMP报头长度则不合理*/
{
//printf("ICMP packets\'s length is less than 8\n");
return -1;
}
/*确保所接收的是我所发的的ICMP的回应*/
if ((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == htons((unsigned short)getpid())))
{
gettimeofday(&tvrecv, NULL);
printf("recv size:%d\n", strlen(icmp->icmp_data));
tvsend = (struct timeval *)icmp->icmp_data;
tv_sub(&tvrecv, tvsend); /*接收和发送的时间差*/
rtt = _sec*1000 + (double)_usec/1000; /*以毫秒为单位计算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);
return 1;
}
else
return -1;
}
/*两个timeval结构相减*/
void tv_sub(struct timeval *out, struct timeval *in)
{
if ((out->tv_usec -= in->tv_usec) < 0)
{
--out->tv_sec;
out->tv_usec += 1000000;
}
out->tv_sec -= in->tv_sec;
}
void statistics(void)
{
struct timeval tvend;
double rstt = 0;
gettimeofday(&tvend, NULL);
tv_sub(&tvend, &tvstart);
rstt = _sec * 1000 + (double)_usec / 1000;
printf("\n--------------------PING statistics-------------------\n");
printf("%d packets transmitted, %d received , %d%% packet lost , time: %.3fms\n",nsend,nreceived,(nsend-nreceived)*100/nsend, rstt);
exit(1);
}
int main(int argc,char *argv[])
{
struct hostent *host;
struct protoent *protocol;
unsigned long inaddr = 0;
struct timeval timeo = {0};
memset(sendpacket, 'a', sizeof(sendpacket));
int size = 50*1024;
if (argc < 2)
{
printf("usage:%s hostname/IP address\n",argv[0]);
exit(1);
}
if ((protocol = getprotobyname("icmp")) == NULL)
{
printf("getprotobyname");
exit(1);
}
/*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/
if ((sockfd = socket(PF_INET, SOCK_RAW, protocol->p_proto)) < 0)/*AF_INET*/
{
printf("socket error\n\r");
exit(1);
}
int iRet = 0;
iRet = setuid(getuid());
if (0 > iRet)
{
printf("Error Setuid\n\r");
close(sockfd);
return -1;
}
_sec = 2;
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(struct timeval));
bzero(&dest_addr,sizeof(dest_addr));
if ((inaddr = inet_addr(argv[1])) == INADDR_NONE)
{
if ((host = gethostbyname(argv[1])) == NULL) /*是主机名*/
{
printf("Host Name Error\n\r");
exit(1);
}
memcpy((char *)&dest_addr.sin_addr, (char *)host->h_addr, host->h_length);
}
else
{
memcpy((char *)&dest_addr.sin_addr.s_addr, (char *)&inaddr, sizeof(inaddr));
}
printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1],inet_ntoa(dest_addr.sin_addr),datalen);
gettimeofday(&tvstart, NULL);
signal(SIGINT, statistics);
while(1)
{
send_packet(); /*发送所有ICMP报文*/
recv_packet(); /*接收所有ICMP报文*/
sleep(1);
}
return 0;
}。

相关文档
最新文档