2

im currently using this method to show my IP address on python,but i realize this is not IP address i needed

hostname = socket.gethostname() 

IPAddr => socket.gethostbyname(hostname)

is there any problem with my code? or is it just a different method to use?

Xantium
  • 11,201
  • 10
  • 62
  • 89
Dud
  • 23
  • 1
  • 4

4 Answers4

3

Try this:

import socket
def get_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # doesn't even have to be reachable
        s.connect(('10.255.255.255', 1))
        IP = s.getsockname()[0]
    except:
        IP = '127.0.0.1'
    finally:
        s.close()
    return IP

Then use get_ip() to get your ip.

Reference : Finding local IP addresses using Python's stdlib

damaredayo
  • 1,048
  • 6
  • 19
3

Windows Specific implementation, runs within 0.1s.

def wlan_ip():
    import subprocess
    result=subprocess.run('ipconfig',stdout=subprocess.PIPE,text=True).stdout.lower()
    scan=0
    for i in result.split('\n'):
        if 'wireless' in i: scan=1
        if scan:
            if 'ipv4' in i: return i.split(':')[1].strip()
print(wlan_ip()) #usually 192.168.0.(DHCP assigned ip)

console OUTPUT for command 'ipconfig':

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::f485:4a6a:e7d5:1b1c%4
   IPv4 Address. . . . . . . . . . . : 192.168.0.131 #<-Returns this part

   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.0.1
nikhil swami
  • 2,360
  • 5
  • 15
2

Get Ip address

import netifaces
netifaces.gateways()
iface = netifaces.gateways()['default'][netifaces.AF_INET][1]

ip = netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']

print(ip)
Shah Vipul
  • 625
  • 7
  • 11
2

This works for me but i changed 'wireless' to 'wi-fi' because the output changes to "Adaptador de LAN inalámbrica Wi-Fi" in Spanish Windows. This code would be more international

    for i in result.split('\n'):
        if 'wi-fi' in i: scan=1

Thanks mate!!

daniburgo
  • 31
  • 1