Skip to content

Instantly share code, notes, and snippets.

@eli-kha
Created July 24, 2023 09:51
Show Gist options
  • Save eli-kha/7e4786c0fe27188559fa39a573cb6b87 to your computer and use it in GitHub Desktop.
Save eli-kha/7e4786c0fe27188559fa39a573cb6b87 to your computer and use it in GitHub Desktop.
a short piece of dependency free code to get the OS netmask
import ipaddress
import platform
import re
import subprocess
def get_netmask(ipv4_address):
"""Gets the computer's current netmask for a given IP.
Returns:
str: The computer's current netmask.
"""
if platform.system() == "Windows":
return get_netmask_windows(ipv4_address)
else:
return get_netmask_linux(ipv4_address)
def get_netmask_windows(ipv4_address):
"""Gets the computer's current netmask on Windows.
Returns:
str: The computer's current netmask.
"""
proc = subprocess.Popen('ipconfig', stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if ipv4_address.encode() in line:
break
mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ', b'').decode()
return mask
def get_netmask_linux(ipv4_address):
"""Gets the computer's current netmask on Linux.
Returns:
str: The computer's current netmask.
"""
proc_output = subprocess.check_output('ip -o addr show'.split(' '))
for line in proc_output.splitlines():
if ipv4_address.encode() in line:
network = line.rstrip().split(b'inet ')[1].split(b' brd')[0].decode()
return str(ipaddress.IPv4Network(network, strict=False).netmask)
if __name__ == '__main__':
import socket
hostname = socket.gethostname()
print(hostname)
ip_address = socket.gethostbyname(hostname)
print(ip_address)
netmask = get_netmask(ip_address)
print(netmask)
if netmask is None:
print('IP not found')
else:
iface = ipaddress.ip_interface(f'{ip_address}/{netmask}')
print(iface.network.network_address)
for ip_addr in iface.network:
print(ip_addr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment