原始套接字--traceroute
#include<stdio.h>
#include<sys/time.h>
#include<errno.h>
#include<signal.h>
#include<time.h>
#include<stdlib.h>
#include<unistd.h>
#include<netdb.h>
#include<string.h>
#include<strings.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in_systm.h>
#include<netinet/ip.h>
#include<netinet/ip_icmp.h>
#include<netinet/udp.h>
#include<netinet/in_systm.h>
#define BUFSIZE 1500
struct rec{
u_short rec_seq;
u_short rec_ttl;
struct timeval rec_tv;
}; char recvbuf[BUFSIZE];
char sendbuf[BUFSIZE]; int datalen;
char *host;
u_short sport,dport;
int nsent;
pid_t pid;
int probe,nprobes;
int sendfd,recvfd;
int ttl,max_ttl;
int verbose; struct proto{
const char*(*icmpcode)(int);
int (*recv)(int,struct timeval*);
struct sockaddr *sasend; //dest addr, the destination
struct sockaddr *sarecv; //recv addr, store who send the message
struct sockaddr *salast;
struct sockaddr *sabind; //bind the source port
socklen_t salen;
int icmpproto;
int ttllevel;
int ttloptname;
}*pr;
int gotalarm;
const char *icmpcode_v4(int code){
static char errbuf[];
switch(code){
case :return("network unreachable");
case :return("host unreachable");
case :return("protocol unreachable");
case :return("port unreachable");
case :return("fragmentation required but DF bit set");
case :return("source route failed");
case :return("destination network unknown");
case :return("destination host unknown");
case :return("source host isolated(obsolete)");
case :return("destination network administartively prohibited");
case :return("destination host administartively prohibited");
case :return("network unreachable for TOS");
case :return("host unreachable for TOS");
case :return("communication error");
case :return("host recedenc violation");
case :return("precedence cutoff in effect");
default:sprintf(errbuf,"unknown code %d",code);
}
return errbuf;
}
void sig_alrm(int signo){
gotalarm=;
return;
}
void tv_sub(struct timeval *out,struct timeval *in){
if((out->tv_usec-=in->tv_usec)<){
--out->tv_sec;
out->tv_sec+=;
}
out->tv_sec-=in->tv_sec;
}
void traceloop(void){
int seq,code,done;
double rtt;
struct rec *rec;
struct timeval tvrecv;
if((recvfd=socket(pr->sasend->sa_family,SOCK_RAW,pr->icmpproto))<){
printf("recvfd:socket failed\n");
return;
}
setuid(getuid());
if((sendfd=socket(pr->sasend->sa_family,SOCK_DGRAM,))<){
printf("sendfd:socket failed\n");
return;
} pr->sabind->sa_family=pr->sasend->sa_family;
sport=(getpid()&0xffff) | 0x8000;
((struct sockaddr_in*)pr->sabind)->sin_port=htons(sport); if(bind(sendfd,pr->sabind,pr->salen)<){
printf("bind error\n");
return;
} sig_alrm(SIGALRM);
seq=;
done=;
for(ttl=;ttl<=max_ttl&&done==;ttl++){
setsockopt(sendfd,pr->ttllevel,pr->ttloptname,&ttl,sizeof(int));//modify ttl
bzero(pr->salast,pr->salen);
printf("%2d ",ttl);
fflush(stdout);
for(probe=;probe<nprobes;probe++){
/*
* *these sendbuf is just
* *used to exam if the received data is sended by our program
* */
rec=(struct rec*)sendbuf;
rec->rec_seq=++seq;
rec->rec_ttl=ttl; gettimeofday(&rec->rec_tv,NULL);
((struct sockaddr_in*)pr->sasend)->sin_port=htons(dport+seq);
if(sendto(sendfd,sendbuf,datalen,,pr->sasend,pr->salen)<){//send to dest with ttl added
perror("bad sendto");
continue;
} //if time_out print * else print info
if((code=(*pr->recv)(seq,&tvrecv))==-){
printf(" *");
}else{
char str[NI_MAXHOST];
if(memcmp(pr->sarecv,pr->salast,pr->salen)!=){
if(getnameinfo(pr->sarecv,pr->salen,str,sizeof(str),NULL,,)==){
printf(" %s (%s)",str,inet_ntoa(((struct sockaddr_in*)pr->sarecv)->sin_addr));
}else{
printf(" %s",inet_ntoa(((struct sockaddr_in*)pr->sarecv)->sin_addr));
}
memcpy(pr->salast,pr->sarecv,pr->salen);
}
tv_sub(&tvrecv,&rec->rec_tv);
rtt=tvrecv.tv_sec*1000.0+tvrecv.tv_usec/;
printf(" %.3f ms",rtt); if(code==-){ //reach the dest
done++;
}else if(code>){
printf(" (ICMP %s)",(*pr->icmpcode)(code));
}
}
fflush(stdout);
}
printf("\n");
}
}
int recv_v4(int seq,struct timeval *tv){
int hlen1,hlen2,icmplen,ret;
socklen_t len;
ssize_t n;
struct ip *ip,*hip;
struct icmp *icmp;
struct udphdr *udp; gotalarm=;
for(;;){
if(gotalarm){
return -;
}
len=pr->salen;
alarm();
n=recvfrom(recvfd,recvbuf,sizeof(recvbuf),,pr->sarecv,&len);//data len
if(n<){
if(errno==EINTR){
continue;
}else{
printf("recvfrom error\n");
return ;
}
}else{
//if recvfrom ok , close the alarm
alarm();
} //read data
ip=(struct ip*)recvbuf;
hlen1=ip->ip_hl<<;//ip len
icmp=(struct icmp*)(recvbuf+hlen1);
if((icmplen=n-hlen1)<){
continue;
}
if(icmp->icmp_type==ICMP_TIMXCEED&&
icmp->icmp_code==ICMP_TIMXCEED_INTRANS){
if(icmplen<+sizeof(struct ip)){
continue;
}
//get icmp data
hip=(struct ip*)(recvbuf+hlen1+);
hlen2=hip->ip_hl<<;
if(icmplen<+hlen2+){
continue;
}
udp=(struct udphdr *)(recvbuf+hlen1++hlen2);
if(hip->ip_p==IPPROTO_UDP&&
udp->source==htons(sport)&&
udp->dest==htons(dport+seq)){
ret=-;
break;
}
}else if(icmp->icmp_type==ICMP_UNREACH){
if(icmplen<+sizeof(struct ip))
continue;
hip=(struct ip*)(recvbuf+hlen1+);
hlen2=hip->ip_hl<<;
if(icmplen<+hlen2+)
continue;
udp=(struct udphdr*)(recvbuf+hlen1++hlen2);
if(hip->ip_p==IPPROTO_UDP&&
udp->source==htons(sport)&&
udp->dest==htons(dport+seq)){
if(icmp->icmp_code==ICMP_UNREACH_PORT)
ret=-; //reach the destination
else
ret=icmp->icmp_code;
break;
}
}
}
gettimeofday(tv,NULL);
return ret;
} struct proto proto_v4={icmpcode_v4,recv_v4,NULL,NULL,NULL,NULL,,IPPROTO_ICMP,IPPROTO_IP,IP_TTL}; int datalen=sizeof(struct rec);
int max_ttl=;
int nprobes=;
u_short dport=+;//hope the port of dest is not used struct addrinfo *host_serv(const char *host,const char *serv,int family,int socktype){
int n;
struct addrinfo hints,*res;
bzero(&hints,sizeof(hints));
hints.ai_flags=AI_CANONNAME;
hints.ai_family=family;
hints.ai_socktype=socktype;
if((n=getaddrinfo(host,serv,&hints,&res))!=){
return NULL;
}
return (res);
}
int main(int argc,char *argv[]){
int c;
struct addrinfo *ai;
struct sigaction s_action;
char h[]={};
while((c=getopt(argc,argv,"m:v"))!=-){
switch(c){
case 'm':
if((max_ttl=atoi(optarg))<){
printf("invalid input\n");
}
break;
case 'v':
verbose++;
break;
case '?':
printf("unrecognized\n");
return -;
}
}
if(optind!=argc-){
printf("error input\n");
return -;
}
host=argv[optind]; pid=getpid(); bzero(&s_action,sizeof(s_action));
s_action.sa_handler=sig_alrm;
s_action.sa_flags=SA_INTERRUPT;
sigaction(SIGALRM,&s_action,NULL); // signal(SIGALRM,sig_alrm);
ai=host_serv(host,NULL,,);
inet_ntop(AF_INET,&((struct sockaddr_in*)(ai->ai_addr))->sin_addr,h,sizeof(h));
printf("traceroute to %s (%s): %d hops max, %d data bytes\n",
ai->ai_canonname?ai->ai_canonname:h,h,max_ttl,datalen); if(ai->ai_family==AF_INET){
pr=&proto_v4;
}else{
printf("UNKNOW address family\n");
return -;
} pr->sasend=ai->ai_addr;
pr->sarecv=(struct sockaddr*)calloc(,ai->ai_addrlen);
pr->salast=(struct sockaddr*)calloc(,ai->ai_addrlen);
pr->sabind=(struct sockaddr*)calloc(,ai->ai_addrlen);
pr->salen=ai->ai_addrlen;
traceloop();
exit();
}
原始套接字--traceroute的更多相关文章
- Linux原始套接字实现分析---转
		
http://blog.chinaunix.net/uid-27074062-id-3388166.html 本文从IPV4协议栈原始套接字的分类入手,详细介绍了链路层和网络层原始套接字的特点及其内核 ...
 - Linux Socket 原始套接字编程
		
对于linux网络编程来说,可以简单的分为标准套接字编程和原始套接字编程,标准套接字主要就是应用层数据的传输,原始套接字则是可以获得不止是应用层的其他层不同协议的数据.与标准套接字相区别的主要是要开发 ...
 - 005.TCP--拼接TCP头部IP头部,实现TCP三次握手的第一步(Linux,原始套接字)
		
一.目的: 自己拼接IP头,TCP头,计算效验和,将生成的报文用原始套接字发送出去. 若使用tcpdump能监听有对方服务器的包回应,则证明TCP报文是正确的! 二.数据结构: TCP首部结构图: s ...
 - 004.UDP--拼接UDP数据包,构造ip头和udp头通信(使用原始套接字)
		
一.大致流程: 建立一个client端,一个server端,自己构建IP头和UDP头,写入数据(hello,world!)后通过原始套接字(SOCK_RAW)将包发出去. server端收到数据后,打 ...
 - 002.ICMP--拼接ICMP包,实现简单Ping程序(原始套接字)
		
一.大致流程: 将ICMP头和时间数据设置好后,通过创建好的原始套接字socket发出去.目的主机计算效验和后会将数据原样返回,用当前时间和返回的数据结算时间差,计算出rtt. 二.数据结构: ICM ...
 - linux原始套接字(4)-构造IP_UDP
		
一.概述 同上一篇tcp一样,udp也是封装在ip报文里面.创建UDP的原始套接字如下: (soc ...
 - linux原始套接字(3)-构造IP_TCP发送与接收
		
一.概述 tcp报文封装在ip报文中,创建tcp的原始套接字如下: sockfd = socket ...
 - linux原始套接字(2)-icmp请求与接收
		
一.概述 上一篇arp请求使用的是链路层的原始套接字.icmp封装在ip数据报里面,所以icmp请 ...
 - linux原始套接字(1)-arp请求与接收
		
一.概述 以太网的arp数据包结构: arp结构op操作参数:1为请求,2为应答. 常用的数据结构如 ...
 
随机推荐
- 2018.7.18 div,section,article的区别和使用
			
section ·<section> 标签定义文档中的节(section.区段).比如章节.页眉.页脚或文档中的其他部分. ·section用作一段有专题性的内容,一般在它里面会带有标题. ...
 - 关于VMware给系统分区扩容的一点经验
			
我的VMware版本是8.0.6 build-1035888,里面安装的是Windows XP SP3 首先,在VM关机状态下使用Hard disk设置中的Utilities下的Expand给整个磁盘 ...
 - 第36章 	SDIO—SD卡读写测试—零死角玩转STM32-F429系列
			
第36章 SDIO—SD卡读写测试 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/f ...
 - Django 入门案例开发
			
Django是一个重量级的web开发框架,它提供了很多内部已开发好的插件供我们使用:这里不去描述 Django直接进入开发过程. Django入门案例分两部分:一.开发环境的配置:二.业务需求分析. ...
 - linux shell 部分问题解决方法
			
1. 判断shell里判断字符串是否包含某个字符 a. 可以用正则式匹配符号 “=~” 举例:str="this is a string" 要想在判断str中是否含有 ...
 - 获取父窗口元素或者获取iframe中的元素(相同域名下)
			
jquery方法 在父窗口中获取iframe中的元素 //方法1 $("#iframe的ID").contents().find("iframe中的元素"); ...
 - ethereum(以太坊)(十一)--字节数组(二)
			
pragma solidity ^0.4.0; contract test { uint [5] T =[1,2,3,4,5] ;//固定长度的数组:可修改数组内值大小,不支持push,不可更改长度 ...
 - 12 new方法和单例、定制访问函数、装饰器
			
new方法和单例.定制访问函数.装饰器 上节课作业解答 # 通过多重继承方法,分别定义出动物,人类,和和荷兰人三种类 class Animal(object): def __init__(self, ...
 - 20145202 《Java程序设计》第四周学习总结
			
继承:打破了封装性 extends 1.提高了代码的复用性. 2.让类与类之间产生了关系,有了这个关系,才有了多态的特性. 3.必须是类与类之间有所属类关系才可以继承. 4.java只支持单继承不支持 ...
 - PHP代码审计6-实战漏洞挖掘-xdcms用户注册页面漏洞
			
xdcms 源码:xdcms v2.0.8 1.配置 [一直下一步(仅为测试)] #数据库账号root,密码为空:管理员账号/密码:xdcms/xdcms #登录后台 2.查看后台登录页面的配置项[x ...