Reputation: 33
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?
Upvotes: 3
Views: 5220
Reputation: 61
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!!
Upvotes: 2
Reputation: 747
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)
Upvotes: 2
Reputation: 2684
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)
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
Upvotes: 3
Reputation: 1079
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
Upvotes: 5