whatspoppin
whatspoppin

Reputation: 383

Get network address of connected interface with Python

How could I get the current network address of a specific interface (not the ip address, but the network address) ?

For example, if I run the following command on terminal ip a show <interace> | grep inet I get a result similar to this.nn

    inet 192.168.43.157/24 brd 192.168.43.255 scope global dynamic noprefixroute wlo1
    inet6 fe80::6877:db06:4b23:7a7c/64 scope link noprefixroute 

In this example my current IP address is 192.168.45.157/24 but the network address (which I am looking for) is 192.168.43.0/24.

How I would get the network address ?

Upvotes: 0

Views: 378

Answers (1)

larsks
larsks

Reputation: 311516

The easiest solution is probably to use the netaddr module:

>>> x = netaddr.IPNetwork('192.168.45.157/24')
>>> x.cidr
IPNetwork('192.168.45.0/24')

Or you can just convert the address into a 32 bit number, convert the prefix into a bitmask, and then apply to the mask:

>>> import socket
>>> addr = '192.168.45.157/24'
>>> ip, prefix = addr.split('/')
>>> mask = 0xFFFFFFFF << (32-int(prefix))
>>> bin(mask)
'0b1111111111111111111111111111111100000000'
>>> ip_bytes = socket.inet_aton(ip)
>>> '.'.join(str(int(x)) for x in struct.pack('>I', struct.unpack('>I', ip_bytes)[0] & mask))
'192.168.45.0'

Upvotes: 1

Related Questions