协议头
IP 协议头
struct ip_hdr
{
unsigned char h_len : 4; //length of header
unsigned char version : 4; //Version of IP
unsigned char tos; //Type of service
unsigned short total_len; //total length of the packet
unsigned short ident; //unique identifier
unsigned short frag_and_flags; //flags
unsigned char ttl; //ttl
unsigned char proto; //protocol(TCP ,UDP etc)
unsigned short checksum; //IP checksum
unsigned int sourceIP;
unsigned int destIP;
};
typedef struct tcp_header
{
unsigned short nSourPort; // 源端口号16bit
unsigned short nDestPort; // 目的端口号16bit
unsigned int nSequNum; // 序列号32bit
unsigned int nAcknowledgeNum; // 确认号32bit
unsigned short nHLenAndFlag; // 前4位:TCP头长度;中6位:保留;后6位:标志位16bit
unsigned short nWindowSize; // 窗口大小16bit
unsigned short nCheckSum; // 检验和16bit
unsigned short nrgentPointer; // 紧急数据偏移量16bit
};
typedef struct udp_header
{
unsigned short nSourPort; // 源端口号16bit
unsigned short nDestPort; // 目的端口号16bit
unsigned short nLength; // 数据包长度16bit
unsigned short nCheckSum; // 校验和16bit
};
ICMP
创建socket 的ICMP 协议参数
int s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
类型8、代码0:回射请求。
类型0、代码0:回射应答。
类型11、代码0:超时。
ICMP 协议头
struct icmp_hdr
{
unsigned char icmp_type; //类型
unsigned char icmp_code; //代码
unsigned short icmp_cksum; //效验和
unsigned short icmp_id; //n 第几个数据 后面三个可以随意填
unsigned short icmp_seq; //n 随机数,用来辨别
unsigned int icmp_data; //GetTickout() 数据
};
发送和接收 sendto(s, buffer, sizeof(buffer), 0, (sockaddr*)&addr, sizeof(addr));
recvfrom(s, recvBuf, sizeof(recvBuf), 0, (sockaddr*)&caddr, &len);
//网际校验和是被校验数据16位值的反码和(ones-complement sum)
WORD CalcCheckSum(IN unsigned short* addr, IN 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) {
*(unsigned char*)(&answer) = *(unsigned char*)w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return (answer);
}
//设置多久没收到包,放弃 [ip] [icmp]
timeval tv = { 3, 0 };
fd_set fd;
FD_ZERO(&fd); //fd.fd_count = 0;
FD_SET(s, &fd);
//fd.fd_count++;
//fd.fd_array[0] = s;
int result = select(0, &fd, NULL, NULL, &tv);