0

WinPcapを使ってネットプログラミングを学んでいます。スニペットは次のとおりです。

int ip_hlen = (ih->ver_ihl & 0xf) * 4; /* get ip header length */
tcp_header *th = (tcp_header *) ((u_char*)ih + ip_len);
int tcp_hlen = (ntohs(th->th_len_resv_code) & 0xf000) >> 12)*4; /* get tcp header length */

問題は、なぜがnotntohsを取得するときにのみ使用される のかということです。 確かに、パラメーターが少し説明しているように、取るだけです。http://msdn.microsoft.com/en-us/library/windows/desktop/ms740075%28v=vs.85%29.aspxtcp_hlenip_hlen
ntohsu_short

ntohs を使用していないときにいつ使用するかについては、まだ戸惑っています。

以下は、IP および TCP パケット定義の構造体です。

/* ipv4 header */
typedef struct ip_header {
    u_char ver_ihl;         /* version and ip header length */
    u_char tos;             /* type of service */
    u_short tlen;           /* total length */
    u_short identification; /* identification */
    u_short flags_fo;       // flags and fragment offset
    u_char ttl;             /* time to live */
    u_char proto;           /* protocol */
    u_short crc;            /* header checksum */
    ip_address saddr;       /* source address */
    ip_address daddr;       /* destination address */
    u_int op_pad;           /* option and padding */
}ip_header;

/* tcp header */
typedef struct tcp_header {
    u_short th_sport;         /* source port */
    u_short th_dport;         /* destination port */
    u_int th_seq;             /* sequence number */
    u_int th_ack;             /* acknowledgement number */
    u_short th_len_resv_code; /* datagram length and reserved code */
    u_short th_window;        /* window */
    u_short th_sum;           /* checksum */
    u_short th_urp;           /* urgent pointer */
}tcp_header;
4

4 に答える 4

2

値が 8 ビット長の場合、エンディアンについて心配する必要はありません。それだけです。バイトを 1 バイトで並べ替えることはできません。

于 2013-11-05T08:34:31.693 に答える
0

ntohsNetwork To Host - Short です。short は 16 ビットです。sockaddr 構造体からポート値を抽出する場合、ntohs を使用する場合の例は、16 ビットの「ポート」値です。

uint16_t portNo = ntohs(sock.sin_port);

最初に oyu がポート番号を sockaddr 構造体に入れるときに、converce、htons を実行する必要があります。

エンディアン変換が必要な場所でのみ使用する必要があります。特に、ヘッダーとプロトコル変数の一部。パケットのユーザー部分 (データ) については、あなたの裁量に任されています。

于 2013-11-05T08:47:57.820 に答える
0

とてもシンプルです。ネットワーク経由で受信した 16 ビット値に遭遇するときはいつでも必要になりますntohs( Short値の Net TO Host 変換を参照)。その理由は、これらの数値をマルチバイトにエンコードするときのさまざまなシステムのエンディアンです。

于 2013-11-05T08:52:21.403 に答える