code来源于《网络编程与分层协议设计》 chap7 ICMP协议程序设计

----没有理解,没有编译,只是敲了出来

ping.h

#define ICMP_ECHOREPLY 0
#define ICMP_ECHO 8

#define BUFSIZE 1500
#define DEFAULT_LEN 56

typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;

struct icmphdr{
u8 type;
u8 code;
u16 checksum;
union{
struct {
u16 id;
u16 sequence;
}echo;
u32 gateway;
struct
{
u16 unused;
u16 mtu;
}frag;
}un;
u8 data[0];
#define icmp_id un.echo.id
#define icmp_seq un.echo.sequence
};
#define ICMP_HSIZE sizeof(struct icmphdr)

struct iphdr{
u8 hlen:4, ver:4;
u8 tos;
u16 tot_len;
u16 id;
u16 frag_off;
u8 ttl;
u8 protocol;
u16 check;
u32 saddr;
u32 daddr;
};

char *hostname;
int datalen = DEFAULT_LEN;
char sendbuf[BUFSIZE];
char recvbuf[BUFSIZE];
int nsent;
int nrecv;
pid_t pid;
struct timeval recvtime;
int sockfd;
struct sockaddr_in dest;
struct sockaddr_in from;
struct sigaction act_alarm;
struct sigaction act_int;

void alarm_handler(int);
void int_handler(int);
void set_sighandler();
void send_ping();
void recv_reply();
u16 checksum(u8 *buf, int len);
int handle_pkt();
void get_statistics(int, int);
void bail(const char *)

ping.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
#include <signal.h>
#include <netinet/in.h>

#include "ping.h"

struct itimerval val_alarm={.it_interval.tv_sec = 1,
.it_interval.tv_usec = 0,
.it_value.tv_sec = 0,
.it_value.tv_usec = 1
};

int main(int argc, char **argv)
{
struct hostent *host;

if (argc < 2){
printf("Usuage: %s hostname\n", argv[0]);
exit(1);
}

if (host = gethostbyname(argv[1]) == NULL){
perror("can not understand the host name");
exit(1);
}

hostname = argv[1];

memset(&dest, 0, sizeof(dest));
dest.sin_family = PF_INET;
dest.sin_port = ntohs(0);
dest.sin_addr = *(struct in_addr *)host->h_addr_list[0];

if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0){
perror("raw socket created error");
exit(1);
}

setuid(getuid());
pid = getpid();

set_sighandler();
printf("Ping %s(%s): %d bytes data in ICMP packets.\n\n",
argv[1], inet_ntoa(dest.sin_addr), datalen);

if ((setitimer(ITIMER_REAL, &val_alarm, NULL)) == -1)
bail("setitimer fails.");

recv_reply();

return 0;
}

void send_ping(void)
{
struct icmphdr *icmp_hdr;
int len;

icmp_hdr = (struct icmphdr *)sendbuf;
icmp_hdr->type = ICMP_ECHO;
icmp_hdr->code = 0;
icmp_hdr->icmp_id = pid;
icmp_hdr->icmp_seq = nsent++;
memset(icmp_hdr->data, 0xff, datalen);

gettimeofday((struct timeval *)icmp_hdr->data, NULL);

len = ICMP_HSIZE + datalen;
icmp_hdr->checksum = 0;
icmp_hdr->checksum = checksum((u8 *)icmp_hdr, len);

sendto(sockfd, sendbuf, len, 0, (struct sockaddr *)&dest, sizeof(dest));
}

void recv_reply()
{
int n, len;
int errno;

n = nrecv = 0;
len = sizeof(from);

while (nrecv < 3){
if ((n = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&from, &len)) < 0){
if (errno == EINTR)
continue;
bail("recvfrom error");
}

gettimeofday(&recvtime, NULL);

if (handle_pkt())

continue;
nrecv++;
}

get_statistics(nsent, nrecv);
}

u16 checksum(u8 *buf, int len)
{
u32 sum = 0;
u16 *cbuf;

cbuf = (u16 *)buf;

while (len > 1){
sum += *cbuf++;
len -= 2;
}

if(len)
sum += *(u8 *)cbuf;

sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);

return -sum;
}

int handle_pkt()
{
struct iphdr *ip;
struct icmphdr *icmp;

int ip_hlen;
u16 ip_datalen;
double rtt;
struct timeval *sendtime;

ip = (struct iphdr *)recvbuf;

ip_hlen = ip->hlen << 2;
ip_datalen = ntohs(ip->tot_len) - ip_hlen;

icmp = (struct icmphdr *)(recvbuf + ip_hlen);

if (checksum(u8 *)icmp, ip_datalen)
return -1;

if(icmp->icmp_id != pid)
return -1;

sendtime = (struct timeval *)icmp->data;
rtt = ((&recvtime)->tv_sec - sendtime->tv_sec)*1000 + ((&recvtime)->tv_usec - sendtime->tv_usec)/1000.0;

printf("%d bytes from %s: icmp_seq = %u ttl=%d rtt=%.3f ms\n",
ip_datalen,
inet_ntoa(from.sin_addr),
icmp->icmp_seq,
ip->ttl,
rtt);

return 0;
}

void set_sighandler()
{
act_alarm.sa_handler = alarm_handler;
if (sigaction(SIGALRM, &act_alarm, NULL) == -1)
bail("SIGALRM handler setting fails.");

act_int.sa_handler = int_handler;
if (sigaction(SIGINT, &act_int, NULL) == -1)
bail("SIGINT handler setting fails.");
}

void get_statistics(int nsent, int nrecv)
{
printf("---%s ping statistics ---\n", inet_ntoa(dest.sin_addr));
printf("%d packets transmitted, %d received, %0.0f%%" "packet loss\n",
nsent, nrecv, 1.0*(nsent - nrecv)/nsent*100);
}

void bail(const char *on_what)
{
fputs(strerror(errno), stderr);
fputs(":", stderr);
fputs(on_what, stderr);
fputc('\n', stderr);
exit(1);
}

void int_handler(int sig)
{
get_statistics(nsent, nrecv);
close(sockfd);
exit(1);
}

void alarm_handler(int signo)
{
send_ping();
}

icmp的程序(ping的实现)的更多相关文章

  1. TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute

    1.IMCP协议介绍 前面讲到了,IP协议并不是一个可靠的协议,它不保证数据被送达,那么,自然的,保证数据送达的工作应该由其他的模块来完成.其中一个重要的模块就是ICMP(网络控制报文)协议. 当传送 ...

  2. 4.ICMP协议,ping和Traceroute

    1.IMCP协议介绍 前面讲到了,IP协议并不是一个可靠的协议,它不保证数据被送达,那么,自然的,保证数据送达的工作应该由其他的模块来完成.其中一个重要的模块就是ICMP(网络控制报文)协议. 当传送 ...

  3. UNIX网络编程——利用ARP和ICMP协议解释ping命令

    一.MTU 以太网和IEEE 802.3对数据帧的长度都有限制,其最大值分别是1500和1492字节,将这个限制称作最大传输单元(MTU,Maximum Transmission Unit)      ...

  4. 利用 Linux tap/tun 虚拟设备写一个 ICMP echo 程序

    本文首发于我的公众号 Linux云计算网络(id: cloud_dev),专注于干货分享,号内有 10T 书籍和视频资源,后台回复「1024」即可领取,欢迎大家关注,二维码文末可以扫. 前面两篇文章已 ...

  5. 利用ARP和ICMP协议解释ping命令

    一.MTU 以太网和IEEE 802.3对数据帧的长度都有限制,其最大值分别是1500和1492字节,将这个限制称作最大传输单元(MTU,Maximum Transmission Unit).如果IP ...

  6. TCP/IP详解学习笔记(4)-ICMP协议,ping和Traceroute【转】

    转自:http://blog.csdn.net/goodboy1881/article/details/670761 1.IMCP协议介绍 前面讲到了,IP协议并不是一个可靠的协议(是一种尽力传送的协 ...

  7. 【网络协议】ICMP协议、Ping、Traceroute

        ICMP协议 ICMP常常被觉得是IP层的一个组成部分,它是网络层的一个协议.它传递差错报文以及其它须要注意的信息.ICMP报文通常被IP层或更高层(TCP.UDP等)使用,它是在IP数据报内 ...

  8. 计算机网络(5)-----ICMP协议和PING程序

    控制报文协议(Internet Control Message Protocol) 定义 它是TCP/IP协议族的一个子协议,用于在IP主机.路由器之间传递控制消息.控制消息是指网络通不通.主机是否可 ...

  9. 应用程序PING发出的是什么报文?

    Ping位于用户层,一般用来测试一台主机是否可达,该程序发送一份ICMP回显请求报文给主机,并等待返回ICMP回显 应答

随机推荐

  1. 51nod1779 逆序对统计

    1779 逆序对统计 基准时间限制:1 秒 空间限制:131072 KB  lyk最近计划按顺序做n道题目,每道题目都分为很多分数档次,lyk觉得这些题太简单了,于是它想到了一个好玩的游戏. lyk决 ...

  2. 以前刷过的数位dp

    TOJ1688: Round Numbers Description The cows, as you know, have no fingers or thumbs and thus are una ...

  3. Welcome-to-Swift-22泛型(Generics)

    泛型代码可以确保你写出灵活的,可重用的函数和定义出任何你所确定好的需求的类型.你可以写出避免重复的代码,并且用一种清晰的,抽象的方式表达出来. 泛型是Swift许多强大特征中的其中一个,许多Swift ...

  4. IE7下li超出ul的固定宽度后溢出bug

    问题描述: ul固定宽度,li浮动超出ul的宽度自动换行,li有左margin,但是靠近ul左边缘的那一列l 的margin设为0,其他浏览器正常,但是在ie7中超出ul宽度后会有一个l溢出并导致出现 ...

  5. 【CCF】网络延时 树搜索

    #include<iostream> #include<cstdio> #include<string> #include<cstring> #incl ...

  6. 表单编码 appliation/x-www-form-urlencoded 与 multipart/form-data 的区别

    当表单使用POST方法时,表单数据提交到服务器端之前有两种编码类型可供选择.默认编码类型为 application/x-www-form-urlencoded,此时所有非字母数字类型的字符都需要转换为 ...

  7. 大规模SOA系统中的分布事务思考

    首先是不建议采用XA两阶段提交方式去处理分布式事务,要知道要能够支持XA分布式事务,必须是要实现XA规范才可以,而Service本身是无状态的,如果这样去做了等于是把Service内部的东西暴露了出去 ...

  8. 【Eclpise】Eclipse中Tomcat启动失败或者是重启失败

    经常在Eclipse中遇到这样的问题,tomcat重启之后失败,而且也停止不了.最好的解决办法就是用DOS命令杀死进程. 比如下面这种情况: 1.查看进程ID  用windows的netstat查看信 ...

  9. 无密码登录Linux

    配置主机A无密码登录主机B 主机A:192.168.1.110 主机B:192.168.1.111 先确保所有主机的防火墙处于关闭状态. 在主机A上执行如下: 1. $cd ~/.ssh 2. $ss ...

  10. upper_bound()和lower_bound()

    ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, la ...