Retrieving network mask in Python

前端 未结 8 967
不知归路
不知归路 2021-01-05 07:59

How would one go about retrieving a network device\'s netmask (In Linux preferably, but if it\'s cross-platform then cool)? I know how in C on Linux but I can\'t find a way

8条回答
  •  悲&欢浪女
    2021-01-05 08:11

    I had the idea to rely on subprocess to use a simple ifconfig (Linux) or ipconfig (windows) request to retrieve the info (if the ip is known). Comments welcome :

    WINDOWS

    ip = '192.168.1.10' #Example
    proc = subprocess.Popen('ipconfig',stdout=subprocess.PIPE)
    while True:
        line = proc.stdout.readline()
        if ip.encode() in line:
            break
    mask = proc.stdout.readline().rstrip().split(b':')[-1].replace(b' ',b'').decode()
    

    UNIX-Like

    ip = '192.168.1.10' #Example
    proc = subprocess.Popen('ifconfig',stdout=subprocess.PIPE)
    while True:
        line = proc.stdout.readline()
        if ip.encode() in line:
            break
    mask = line.rstrip().split(b':')[-1].replace(b' ',b'').decode()
    

    IP is retrieved using a socket connection to the web and using getsockname()[0]

提交回复
热议问题