Skip to content

Instantly share code, notes, and snippets.

@gustavorv86
Last active December 7, 2020 16:46
Show Gist options
  • Save gustavorv86/2bd2b15a802fec23619f24994d5e726b to your computer and use it in GitHub Desktop.
Save gustavorv86/2bd2b15a802fec23619f24994d5e726b to your computer and use it in GitHub Desktop.
Calculate all network IP adresses from a IP and a netmask
#!/usr/bin/env python3
import struct
import socket
def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]
def int2ip(addr):
return socket.inet_ntoa(struct.pack("!I", addr))
def get_ip_list(ip: str, netmask: str):
i_ip = ip2int(ip)
i_netmask = ip2int(netmask)
i_network = i_ip & i_netmask
i_bcast = i_network | (~ i_netmask & 0x0FFFF)
ip_list = list()
for i_ip in range(i_network + 1, i_bcast):
s_network = int2ip(i_ip)
ip_list.append(s_network)
return ip_list
if __name__ == "__main__":
## Example
ip = "10.8.9.210"
netmask = "255.255.255.128"
ip_list = get_ip_list(ip, netmask)
for ip in ip_list:
print(ip)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment