ip address and network

Denis S. Otkidach ods at strana.ru
Thu Oct 23 11:32:34 EDT 2003


On Thu, 23 Oct 2003, Ruslan Spivak wrote:

RS> I need to do the following:
RS> i have ip address(a lot of different ip addresses) and i
RS> need to
RS> determine if it belongs to some network. (for example ip -
RS> 193.108.240.17, network 193.108.240.0/22).
RS> How can i solve this?

It's simple:

>>> from socket import inet_aton
>>> from struct import unpack
>>> mask = 2**22-1 << 32-22
>>> unpack('!i', inet_aton('193.108.240.17'))[0] & mask ==
unpack('!i', inet_aton('193.108.240.0'))[0] & mask
True

Or look at ipaddr.py:
http://py.vaults.ca/apyllo.py?i=35559588

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]






More information about the Python-list mailing list