我在犹豫什么时候用ntohs和ntohl。 我知道你什么时候在unt16_t和ntohl uint32_t上使用ntohs。 但是,指定了unsigned int或特定位数的函数(u_int16_t doff:4; )呢? 你什么时候在c上用ntohs和ntohl?
这是我的工作代码,在于向世界证明问题:
//utility/debuggingmethodfordumpingrawpacketdata
void dump (constunsignedchar * data,int length ) )
unsigned int i;
static unsigned long pcount=0;
//解码包标题
struct ether _ header * eth _ header=(struct ether _ header * ) data;
printf ((n (n===packet % LD header==(n ),pcount );
printf((nsourceMAC: );
for(I=0; i 6; I ) {
printf(x ),eth_header-ether_shost[i];
if(I5 ) {
打印(: );
}
}
打印((ndestinationmac : );
unsignedshortethernet _ type=ntohs (eth _ header-ether _ type );
printf((ntype:%Hu(n ),以太网_ type ); //Why not nthos?
以太网_ type==ethertypekwdqj ) { //IP Header
printf((n==IPheader==(n ) );
structIP*IP_HDR=(structIP* ) (datasizeof ) structether_header );
unsigned intsize _ IP=IP _ HDR-IP _ HL * 4; //why no nthos or nthol
printf((nip_HDR-IP_HL:%u ),ip_hdr-ip_hl ); //why no nthos or nthol
printf(nipversion:%u )、ip_hdr-ip_v ); //why no nthos or nthol
printf((nheaderlength:%u ),ip_hdr-ip_hl ); //why no nthos or nthol
printf((ntotallength:%Hu ),ntoHs ) IP_HDR-IP_Len ); //? is this right?
//TCP Header
printf((n==TCPheader==(n ) );
struct tcphdr * TCP _ HDR=(struct tcphdr * ) (datasizeof(structether_header ) size_ip );
unsigned intsize _ TCP=TCP _ HDR-doff * 4; //why no nthos or nthol
printf((nsourceport:% ) priu16,ntohs ) TCP_HDR-th_sport );
printf((ndestinationport:% ) priu16,ntohs ) TCP_HDR-th_dport );
printf((nfin:% ) priu16,tcp_hdr-fin ); //As this is 1 bit,both nthos or nthol will work
printf((nURG:% ) priu16,tcp_hdr-urg ); //As this is 1 bit,both nthos or nthol will work
printf((nack_seq:% ) priu32,ntohl ) TCP_HDR-ack_seq );
u _ int 16 _ tsource port=ntohs (TCP _ HDR-th _ sport );
u _ int 16 _ tdestinationport=ntohs (TCP _ HDR-th _ sport );
源端口==80||目标端口==80 ) {
printf((n(nport80! n ';
//Transport payload!
printf((n(==TCPpayloaddata==(n ) );
//decodepacketdata (skippingovertheheader ) )。
unsignedintheaders _ size=eth _ hlen size _ IP size _ TCP;
unsignedintdata _ bytes=length-headers _ size;
constunsignedchar * payload=data headers _ size;
const static int output_sz=500; //Output this many bytes at a time
while(data_bytes0) {
int output _ bytes=data _ bytes output _ SZ? data_bytes : output_sz;
//printdatainrawhexadecimalform
printf () |;
//打印数据in ascii form
for(I=0; i output_bytes; I ) {
char byte=payload[i];
if((byte31byte127 )|| byte=='n ' ) )
//Byte is in printable ascii range
printf('%c”,byte; //why no nthos or nthol
} else {
printf ('.' );
}
}
payload =output_bytes;
data_bytes -=output_bytes;
}
}
}
pcount;
}
正如你所看到的,我用的是ntohs和/或ntohl,但我有时不用。 我不知道什么时候用哪个。