0

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 ?

1
  • I believe the OP is looking get this information in Python, which makes the question more programming-related. Commented Jan 5, 2021 at 21:59

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.