关于ip包头的生成

在发送ip数据包时一般的数据包头部都可以调用系统函数生成,在我们研究ping命令时有时需要自己构造和解构ip包头。

在一般情况下ip数据包包头有20个Byte,不包括ip数据包选项。

ip头部结构为:

/*The IP header */
typedef struct iphdr {
unsigned char h_len:4; // length of the header 4 bit
unsigned char version:4; // Version of IP 4 bit
unsigned char tos; // Type of service 16 bit
unsigned short total_len; // total length of the packet 16 bit
unsigned short ident; // unique identifier 16 bit
unsigned short frag_and_flags; // flags 16 bit
unsigned char ttl; // 生存时间 8 bit
unsigned char proto; // protocol (TCP, UDP etc) 8 bit
unsigned short checksum; // IP checksum

unsigned int sourceIP;
unsigned int destIP;

}IpHeader;

通过数据对位解析:

 1 //解构ip包
2 //buf 接收到的数据
3 //bytes 接收到的字节数
4 //from 发送端的地址信息
5 int decode_ip(char *buf, int bytes,struct sockaddr_in *from)
6 {
7 IpHeader *iphdr;
8 iphdr = (IpHeader *)buf;
9 iphdrlen = (iphdr->h_len) * 4 ; // 获得包头长度
10
11 //相应的字段在解构体内
12 }





 

 

 

posted @ 2012-03-07 16:36  chen-zx  阅读(194)  评论(0)    收藏  举报