2

I want to get my local IP address and also the subnet mask of the network with a python code. I tried this code for getting the IP address:

import socket
print socket.gethostbyname(socket.gethostname())

But I got this IP > 169.254.236.99, which is not my local IP address.

So maybe you can help me to do it? Thanks.

Edit: I found nice solution for the IP address that works on both Linux and Windows

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])

So if you can help me with the subnet mask it will be pretty helpful :)

Adi Koch
  • 91
  • 9
  • the problem is your Computer has multiple network adaptors and multiple addresses. the 169 is on a virtual interface to use for pcap. You can use something like `ifaddr` from pip to list all of them. – Doon Mar 10 '19 at 00:15
  • You are right, i found the solution. Maybe you can help me with the subnet mask? – Adi Koch Mar 10 '19 at 00:21
  • Do you still need an IP mask ? Try this: https://stackoverflow.com/a/10508732/9808870 However, you must know the number of bits for the mask (usually it is unsigned 32bit integers). – s3n0 Mar 10 '19 at 00:32
  • This is not what I need because I don't know the number of bits of the mask.. but thanks for your comment – Adi Koch Mar 10 '19 at 00:35
  • I'm sorry, I've modified my comment. The mask for IPv4 is typically 32bit (4 bytes x 8 bit). – s3n0 Mar 10 '19 at 00:37
  • Yes but I have only my local IP address, I can not get from it the subnet mask. – Adi Koch Mar 10 '19 at 00:39
  • Another one option would also be to grab the data from `ipconfig` command - using the another module and method `subprocess.Popen()` or `os.system()`. With the help of the regex - python module `re`. But it takes a little more processor time. So only in the case if he used it irregularly and less often, it could be used. – s3n0 Mar 10 '19 at 01:25

1 Answers1

0

The loopback is Not generally but always 127.0.0.1 You Local IP (LAN) is 192.168.1.11 (wifi)

Have a look at this: Netifaces

That's a little thingy that will probably help you further. :-)

Dakta Moriamé
  • 136
  • 2
  • 5