
上QQ阅读APP看书,第一时间看更新
How to do it...
Python's socket library has utilities for converting from a network byte order to host byte order and vice versa. You may want to become familiar with them, for example, ntohl()/htonl().
Let us define the convert_integer() function, where the ntohl()/htonl() socket class functions are used to convert IP address formats.
Listing 1.5 shows integer_conversion as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import socket def convert_integer(): data = 1234 # 32-bit print ("Original: %s => Long host byte order: %s, Network byte order: %s" %(data, socket.ntohl(data), socket.htonl(data))) # 16-bit print ("Original: %s => Short host byte order: %s, Network byte order: %s" %(data, socket.ntohs(data), socket.htons(data))) if __name__ == '__main__': convert_integer()
If you run this recipe, you will see the following output:
$ python 1_5_integer_conversion.py Original: 1234 => Long host byte order: 3523477504,
Network byte order: 3523477504 Original: 1234 => Short host byte order: 53764,
Network byte order: 53764