协议层
MAC
typedef struct ether_header
{
uint8_t eth_dest[ETHER_ADDR_LEN];
uint8_t eth_src[ETHER_ADDR_LEN];
uint16_t eth_type;
} ether_header_t;
IP
typedef struct ip_header
{
uint8_t ip_vhl;
uint8_t ip_tos;
uint16_t ip_len;
uint16_t ip_id;
uint16_t ip_off;
uint8_t ip_ttl;
uint8_t ip_proto;
uint16_t ip_checksum;
uint32_t ip_src;
uint32_t ip_dest;
} ip_header_t;
UDP
typedef struct udp_header
{
uint16_t udp_src_port;
uint16_t udp_dst_port;
uint16_t udp_len;
uint16_t udp_crc;
} udp_header_t;
头部校验和计算方法
uint16_t ip_checksum(unsigned char *buffer, int length)
{
uint32_t sum = 0;
for (int i = 0; i < length - 1; i += 2)
{
uint16_t word = (buffer[i] << 8) + buffer[i + 1];
sum += word;
}
if (length % 2)
{
uint16_t word = (buffer[length - 1] << 8) + 0;
sum += word;
}
while (sum >> 16)
{
sum = (sum & 0xFFFF) + (sum >> 16);
}
sum = ~sum;
return (uint16_t)sum;
}
ip_header_t ip_ = {0};
ip_.ip_vhl = (4 << 4) | (sizeof(ip_header_t) / sizeof(uint32_t));
ip_.ip_tos = 0;
ip_.ip_len = htons(0x123);
ip_.ip_id = htons(0x81234);
ip_.ip_off = htons(0x4000);
ip_.ip_ttl = 0x40;
ip_.ip_proto = 0x11;
ip_.ip_checksum = 0;
ip_.ip_src ;
ip_.ip_des;
uint16_t checksum = ip_checksum((unsigned char *)&ip_, sizeof(ip_));
ip_.ip_checksum = htons(checksum);