If you ever need to write a low-level network application, it may be necessary to handle the low-level data transmission over the wire between two machines. This operation requires some sort of conversion of data from the native host operating system to the network format and vice versa. This is because each one hat its own specific representation of data.
编写底层低层网络应用时,或许需要处理通过电缆在两台设备之间传送的低层数据。在这种操作中,需要把主机操作系统发出的数据转换成网络格式,或者做逆向转换,因为这两种数据的表示方式不一样。
1. 代码
1 # 主机字节序和网络字节序之间的相互转换 2 3 import socket 4 5 6 def convert_integer(): 7 data = 1234 8 # 32-bit 9 print("Original: %s => Long host byte order: %s, Network byte order: %s" 10 % (data, socket.ntohl(data), socket.htonl(data))) 11 # 16-bit 12 print("Original: %s => Short host byte order: %s, Network byte order: %s" 13 % (data, socket.ntohs(data), socket.htons(data))) 14 15 if __name__ == ‘__main__‘: 16 convert_integer()
2. ntohl()、ntohs()、htonl()和htons()解释
1 def ntohl(integer): # real signature unknown; restored from __doc__ 2 """ 3 ntohl(integer) -> integer 4 5 Convert a 32-bit integer from network to host byte order. 6 """ 7 return 0 8 # 将网络字节顺序转换成主机字节顺序(32bit) 9 10 def ntohs(integer): # real signature unknown; restored from __doc__ 11 """ 12 ntohs(integer) -> integer 13 14 Convert a 16-bit integer from network to host byte order. 15 """ 16 return 0 17 # 将网络字节顺序转换成主机字节顺序(16bit) 18 19 def htonl(integer): # real signature unknown; restored from __doc__ 20 """ 21 htonl(integer) -> integer 22 23 Convert a 32-bit integer from host to network byte order. 24 """ 25 return 0 26 # 将主机字节顺序转换成网络字节顺序(32bit) 27 28 def htons(integer): # real signature unknown; restored from __doc__ 29 """ 30 htons(integer) -> integer 31 32 Convert a 16-bit integer from host to network byte order. 33 """ 34 return 0 35 # 将主机字节顺序转换成网络字节顺序(16bit)
3.网络字节顺序和主机字节顺序解释
网络字节顺序NBO(Network Byte Order): 按从高到低的顺序存储,在网络上使用统一的网络字节顺序,可以避免兼容性问题。 主机字节顺序(HBO,Host Byte Order): 不同的机器HBO不相同,与CPU设计有关,数据的顺序是由cpu决定的,而与操作系统无关。 如 Intel x86结构下, short型数0x1234表示为34 12, int型数0x12345678表示为78 56 34 12 如 IBM power PC结构下, short型数0x1234表示为12 34, int型数0x12345678表示为12 34 56 78
时间: 2024-10-05 23:58:21