0

I'm looking for a way to get output like "192.168.1.0/24".

I know I can get my IP address by

my_ip = socket.gethostbyname(socket.gethostname())

but that's not the thing I want. I should also mention that I'm using Linux

Atropin
  • 41
  • 3
  • Are you looking for the subnet for your network adapter? Or do you want a way to convert a mask to the bit count notation? – Tim Roberts Jun 23 '22 at 18:44
  • I'm looking for both network and a subnet mask, ideally in a notation shown above – Atropin Jun 23 '22 at 18:46
  • 1
    `cat /proc/net/fib_trie` has the information you want. It's also in the `ip address` output. – Tim Roberts Jun 23 '22 at 18:53
  • okay but how do I extract the info from there? I don't think it is tied to a specific line – Atropin Jun 23 '22 at 19:09
  • tink: I don't need my IP address, I need a network I'm connected to, plus subnet mask – Atropin Jun 23 '22 at 19:12
  • Of course it is tied to a specific line. The IP and subnet are part of the configuration of a network adapter, usually assigned by DHCP. The subnet mask just tells it how to reach the router. You can have several adapters, and a single adapter can have several address assignments. – Tim Roberts Jun 23 '22 at 19:29
  • https://stackoverflow.com/a/66534468/1394729 - shows how to get the netmask. Use https://stackoverflow.com/questions/50867435/get-subnet-from-ip-address for the network – tink Jun 23 '22 at 19:55

1 Answers1

0

Finally found a soulution

import socket
import fcntl
import struct
import ipaddress

iface = "enp0s3"
subnet_mask = socket.inet_ntoa(fcntl.ioctl(socket.socket(socket.AF_INET, socket.SOCK_DGRAM), 35099, struct.pack(b'256s', iface.encode()))[20:24])
my_ip = socket.gethostbyname(socket.gethostname())
network = ipaddress.IPv4Network(my_ip+"/"+subnet_mask, strict=False)
print(network)

prints 192.168.1.0/24

Atropin
  • 41
  • 3