htons / htonl、ntohs / ntohl、inet_addr、inet_ntoa



Htons Htonl Ntohs Ntohl Inet_addr Inet_ntoa



1.htons / htonl

#include uint32_t htonl(uint32_t hostlong) uint16_t htons(uint16_t hostshort)

どちらの関数も、符号なし整数をホストバイトオーダーからネットワークバイトオーダーに変換します。
違いはなんですか?
htonl()はそれを意味します 32 ビットホストのバイト順序はに変換されます 32 ビットネットワークのバイトオーダーhtons()は、 16 ビットホストのバイト順序はに変換されます 16 ビットのネットワークバイトオーダー。 (IPアドレスは32ビット、ポート番号は16ビットです)
hton(16ビット)を使用したポート変換の場合、htonlを使用すると、ポート番号が2ビットであるため、上位2ビットはすべて0になり、変換されるデータが16ビットを超える場合は割り当ては0になります。 htonlを使用できます。 htonsを使用すると、データは破棄されます。
2.ntohs / ntohl



#include uint32_t ntohl(uint32_t netlong) uint16_t ntohs(uint16_t netshort)

どちらの関数も、符号なし整数をネットワークエンディアンからホストエンディアンに変換します。
違いはなんですか?
ntohl()は、32ビット番号がネットワークバイトオーダーからホストバイトオーダーに変換され、ホストバイトオーダーで表される32ビット番号を返すことを意味します。
ntohs()は、16ビットの数値がネットワークバイトオーダーからホストバイトオーダーに変換され、ホストエンディアンで表される16ビットの数値を返すことを意味します。
3.inet_addr

#include #include #include in_addr_t inet_addr(const char *cp)

パラメータ:cp:文字列、ドット付き10進IPアドレス
機能:ドット付き10進IPアドレスをネットワークバイトオーダー整数値に変換します
例:inet_addr( '192.168.0.0')文字列形式のIPアドレスをネットワークバイト順の整数値に変換します。
4.inet_ntoa



#include #include #include char *inet_ntoa(struct in_addr in)

パラメータ:struct in_addr:ネットワーク上のIPアドレス、構造体です
機能:10進数のネットワークバイトオーダーをドット付き10進数のIPアドレスに変換します
戻り値:成功:ドット付き10進IPアドレスを格納する静的バッファーへの文字ポインターを返します。エラー:NULL
htons / htonl、ntohs / ntohl、inet_addr、inet_ntoaの特定のアプリケーションについては、次のブログを参照してください:/ ttps://mp.csdn.net/postedit/82720870

struct sockaddr_in{ Short sin_family//AF_INET (address family) PF_INET (protocol family) Unsigned short sin_port/*Portnumber (must use the network data format, ordinary numbers can be converted to network data format numbers using the htons() function)*/ Struct in_addr sin_addr//32-bit IP address Unsigned char sin_zero[8]// has no practical meaning, just to align with the SOCKADDR structure in memory*/ } Also struct in_addr : typedef uint32_t in_addr_t struct in_addr { in_addr_t s_addr }