how do I get my ip adress and subnet mask from the computer(windows) using python?
Asked
Active
Viewed 1,304 times
-5
-
2You are asking 2 questions here: 1. How do you get the internal IP and subnet mask in Python. 2. How do you convert an IP + subnet mask to IP/CIDR. I believe both questions have a good duplicate – DeepSpace Mar 21 '19 at 20:46
-
3Possible duplicate of [Finding local IP addresses using Python's stdlib](https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib) – jeanggi90 Mar 21 '19 at 20:50
1 Answers
2
For you second question, you can do this:
def int_address(address):
return list(map(int, address.split(".")))
def bit_len(mask):
return "".join(bin(m)[2:] for m in mask).find('0')
def prefix(mask, ip):
return ".".join(str(m & i) for m, i in zip(mask, ip))
def cidr(mask, ip):
mask = int_address(mask)
ip = int_address(ip)
return prefix(mask, ip)+"/"+str(bit_len(mask))
print(cidr("255.255.255.0", "10.0.0.1"))
The bit_len
is a bit hacky, I think a better solution can be found.

cglacet
- 8,873
- 4
- 45
- 60