Hi there,
I was wondering if anyone can give some advise/tips on this. My goal is to figure out the broadcast address. The way I think I should do is:

  • get/detect the IP address and the subnet mask or CIDR
  • convert the mask to binary form
  • count the number of tailing 0s and apply the formula: m=2^n, where n is the number of the 0s
  • replace the last bit of the IP address with the the number: m-1

and that should be the broadcast address.

My question is: what's the best way of getting [or detect] the IP address and subnet mask? Having said that, I mean which is OS independent. I can use "ifconfig" to figure out that info but again "ifconfig" implementation varies from distro to distro and definitely that not gonna work on windows. I tried using socket.gethostbyname(socket.gethostname()) and also socket.gethostbyname(socket.getfqdn()) but that doesn't return the correct IP address if the "/etc/hosts" file is not properly written. Otherwise it returns the loop back address. I'm stuck here. I'm sure there must be a better way of doing this. Anyone out here got something for me?
Thanks in advance. Cheers!!!

7 Years
Discussion Span
Last Post by MacUsers

hi slate,
Thanks for trying to help me out.
Actually my problem is not with calculation but with the with getting the IP itself, in the first place. I didn't know about ipcalc though, but it seems like one need to know the IP and the subnet mask/CIDR first to use it. I've already [kinda] solved that part. But ipcalc gonna make my job lot easier, for sure. Cheers!!!

Edited by MacUsers: n/a


Just for the future reference, in case anyone else is also looking for the same thing, I'm answering to my own question. I found this solution and it works on OS X and Linux.

## broadcast address
osSys = "uname -s"
BSD = "ifconfig | grep -w broadcast | cut -d\  -f 6"
LNX = "ip -o addr show | grep -w inet | grep -e eth | cut -d\  -f 9"
if commands.getoutput(osSys) == "Linux":
    bCast = commands.getoutput(LNX)
elif commands.getoutput(osSys) == "Darwin":
    bCast = commands.getoutput(BSD)
    print "System not supported!!"

Hope this helps. cheers!!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.