我正在尝试解析一个TCP数据包,然后将其分配给指向有效负载开始的指针。
我正在使用C语言编写代码,以下是我的代码:
我确定这段代码有错误,因为端口号都很奇怪。没有一个分配到80。输出的IP版本也可能非常奇怪(比如版本11)。我做错了什么?谢谢!
另外,我不确定何时使用nthos以及何时不使用。我知道nthos用于16位无符号整数,而nthol用于32位无符号整数,但我知道你不能在那些数据包中的所有内容中都使用它们(例如:tcp_hdr->fin)。为什么某些事情可以使用,而其他事情则不行?
非常感谢!
编辑:
感谢Art修复了大部分问题。我编辑了我的tcp_hdr和ip_hdr,所以现在括号是正确的!
我还有两个问题:
我正在使用C语言编写代码,以下是我的代码:
void dump(const unsigned char *data, int length) { //*data contains the raw packet data
unsigned int i;
static unsigned long pcount = 0;
// Decode Packet Header
struct ether_header *eth_header = (struct ether_header *) data;
printf("\n\n === PACKET %ld HEADER ===\n", pcount);
printf("\nSource MAC: ");
for (i = 0; i < 6; ++i) {
printf("%02x", eth_header->ether_shost[i]); //? Why don't i use nthos here?
if (i < 5) printf(":");
}
unsigned short ethernet_type = ntohs(eth_header->ether_type);
printf("\nType: %hu\n", ethernet_type);
if (ethernet_type == ETHERTYPE_IP) { //IP Header
printf("\n == IP HEADER ==\n");
struct ip *ip_hdr = (struct ip*) data + sizeof(struct ether_header);
unsigned int size_ip = ip_hdr->ip_hl * 4;
printf("\nIP Version: %u", ip_hdr->ip_v); //? Nthos or no nthos
printf("\nHeader Length: %u", ip_hdr->ip_hl); //? Nthos or no nthos
printf("\nTotal Length: %hu", ntohs(ip_hdr->ip_len)); //? Nthos or no nthos
// TCP Header
printf("\n== TCP HEADER ==\n");
struct tcphdr *tcp_hdr = (struct tcphdr*) data + sizeof(struct ether_header) + size_ip;
printf("\n Source Port: %" PRIu16, nthos(tcp_hdr->th_sport));
printf("\n Destination Port: %" PRIu16, nthos(tcp_hdr->th_dport));
printf("\n fin: %" PRIu16, tcp_hdr->fin);
printf("\n urg: %" PRIu16, tcp_hdr->urg);
printf("\n ack_seq: %" PRIu32, ntohl(tcp_hdr->ack_seq));
//Transport payload! i.e. rest of the data
const unsigned char *payload = data + ETH_HLEN + size_ip + sizeof(struct tcphdr) + tcp_hdr->doff;
}
我确定这段代码有错误,因为端口号都很奇怪。没有一个分配到80。输出的IP版本也可能非常奇怪(比如版本11)。我做错了什么?谢谢!
另外,我不确定何时使用nthos以及何时不使用。我知道nthos用于16位无符号整数,而nthol用于32位无符号整数,但我知道你不能在那些数据包中的所有内容中都使用它们(例如:tcp_hdr->fin)。为什么某些事情可以使用,而其他事情则不行?
非常感谢!
编辑:
感谢Art修复了大部分问题。我编辑了我的tcp_hdr和ip_hdr,所以现在括号是正确的!
我还有两个问题:
- 负载的前10个字节有奇怪的符号(所以我认为我没有正确分配负载)。
- 我仍然不确定何时使用nthos / nthol。 我知道u_int16_t是ntohs,u_int32_t是ntohl。 但是对于带符号int或无符号short int的内容呢?例如,我没有为ip_v使用ntohs或nthol才能使其正常工作。 为什么不呢? “ip_hdr-> ip_hl”是nthol吗?等等...
编辑2
我已经修复了我的负载未正确输出的原因(这是因为我计算TCP_header大小错误)。
尽管我仍然困惑于何时使用nthos,但我会将其作为单独的问题放在这里,因为我认为我在这篇文章中提出了太多问题!
ntohs
将一个短整型(16位)从网络字节序转换为主机字节序。 - Some programmer dude