|I l@ve RuBoard|
10.6 Converting IP Addresses
Credit: Alex Martelli, Greg Jorgensen
import socket, struct def dottedQuadToNum(ip): "convert decimal dotted quad string to long integer" return struct.unpack('>L',socket.inet_aton(ip)) def numToDottedQuad(n): "convert long int to dotted quad string" return socket.inet_ntoa(struct.pack('>L',n))
To split an IP address into network and host portions, we just need to apply a suitable binary mask to the long integer form of the IP address:
def makeMask(n): "return a mask of n bits as a long integer" return (2L<<n-1)-1 def ipToNetAndHost(ip, maskbits): "return tuple (network, host) dotted-quad addresses given IP and mask size" # by Greg Jorgensen n = dottedQuadToNum(ip) m = makeMask(maskbits) host = n & m net = n - host return numToDottedQuad(net), numToDottedQuad(host)
The format we use for the struct.pack and struct.unpack calls must start with a '>', which specifies big-endian byte order. This is the network byte order used by the socket.inet_aton and socket.inet_ntoa functions. If you omit the '>', struct instead uses the native byte order of the machine the code is running on, while the socket module still uses big-endian byte order.
However, the bit mask invariably had a certain number (N) bits that were 1 followed by 32-N bits that were 0. The current form, which is much more compact and readable, is therefore structured like:
The part after the / is just N: the number of bits that must be 1 in the mask. If you know about a network that is expressed in this form, you can use the functions in this recipe to check if a host is within that network:
def isHostInNet(host_ip, net_ip_with_slash): net_ip, mask_length = net_ip_with_slash.split('/') mask_length = int(mask_length) net_net, net_host = ipToNetAndHost(net_ip, 32-mask_length) assert net_host == '0.0.0.0' host_net, host_host = ipToNetAndHost(host_ip, 32-mask_length) return host_net == net_net
Note that the slash format of network addresses gives the number of bits in the mask for the network, although we wrote the ipToNetAndHost function to take the number of bits in the mask for the host. Therefore, we pass 32-mask_length in the two calls that isHostInNet makes to the ipToNetAndHost function. The assert statement is not strictly necessary, but it does assure us that the argument passed as net_ip_with_slash is correct, and (as assert statements usually do) serves as a general sanity check for the proceedings.
10.6.4 See Also
Documentation for the standard library modules socket and struct in the Library Reference.
|I l@ve RuBoard|