Skip to content
Advertisement

Unable to get the network’s broadcast address with Python’s Ipaddress module

This is my code to get the broadcast address of my network:

JavaScript

It first gets the local IP and then the subnet mask. I know I can do a binary calculation to obtain the broadcast address, but I am wondering why the above function does not work.

This outputs IPv4Address('192.168.1.47'). I expect it to output 192.168.1.255. Why does this happen?

Advertisement

Answer

Address IP can be used with different masks – all depend on user/admin decision and settings in your system – and you can’t expect that it will automatically use 24 for your address.

Socket gives IP but it doesn’t give mask.

If you not set mask in IPv4Network (or other command) then it will use 32 which later gives you 192.168.1.47 instead of expected 192.168.1.255

If you set manually 24 with your IP to create Interface then you can get expected network and expected broadcast.

JavaScript

Result

JavaScript

To get correct mask you would have to ask system for this. Maybe with psutil or using subprocess with system command ipconfig (Windows) or ifconfig (Linux)

But if you have installed psutil then you don’t need previous method

JavaScript

Result (for my Linux)

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement