If you ever need to write a low-level network application, it could be necessary to handle the low-level data transmission O Ver The wire between the machines. This operation requires some sort of conversion of data from the native host operating system to the network format and VI Ce versa. This was because each of the one hat its own specific representation of data.
When writing underlying low-level network applications, it may be necessary to handle low-level data that is routed between two devices via a cable. In this operation, the data emitted from the host operating system needs to be converted into a network format, or reversed, because the two data are represented differently.
1. Code
1 #conversion between host byte order and network byte order2 3 ImportSocket4 5 6 defConvert_integer ():7data = 12348 #32-bit9 Print("Original:%s = Long host byte order:%s, Network byte order:%s"Ten%(data, Socket.ntohl (data), SOCKET.HTONL (Data ))) One #16-bit A Print("Original:%s = Short host byte order:%s, Network byte order:%s" -%(data, Socket.ntohs (data), socket.htons (Data ))) - the if __name__=='__main__': -Convert_integer ()
2. Explanations of Ntohl (), Ntohs (), htonl () and htons ()
1 defNtohl (integer):#real signature unknown; restored from __doc__2 """3 Ntohl (integer), integer4 5 Convert a 32-bit integer from the network to host byte order.6 """7 return08 # Convert network byte order to host byte order (32bit)9 Ten defNtohs (integer):#real signature unknown; restored from __doc__ One """ A ntohs (integer), integer - - Convert a 16-bit integer from the network to host byte order. the """ - return0 - # Convert network byte order to host byte order (16bit) - + defHtonl (integer):#real signature unknown; restored from __doc__ - """ + htonl (integer), integer A at Convert a 32-bit integer from the host to network byte order. - """ - return0 - # Convert host byte order to network byte order (32bit) - - defHtons (integer):#real signature unknown; restored from __doc__ in """ - htons (integer), integer to + Convert a 16-bit integer from the host to network byte order. - """ the return0 *# Convert host byte order to network byte order (16bit)
3. Network byte order and host byte order interpretation
The int type number 0x12345678 is expressed asthe 0x12345678, the int number is represented as 12 34 56 78
Python Network programming--conversion between host byte order and network byte order