Saturday, February 6, 2016

Python code to find my IP address, run on Raspberry Pi/Raspbian Jessie


Python example code to find my IP address, run on Raspberry Pi/Raspbian Jessie.


PythonListInetAddress.py
import socket
import commands

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#connect to any target website
s.connect(('google.com', 0))
ipAddress = s.getsockname()[0]
s.close()

print("IP Address from socket:")
print(ipAddress)
print("")

print("ifconfig output:")
print(commands.getoutput("ifconfig"))
print("inet addr from ifconfig output:")
print(commands.getoutput("ifconfig").split("\n")[1].split()[1][5:])

remark@2016-02-14:
Refer to comment from baskeddy:
Have to changed the port to 80 in the socket.connect()

From: 
s.connect(('google.com', 0))

to:

s.connect(('google.com', 80))

Related:
Java code to listing Network Interface Addresses
C example to getting IP address from a network interface

2 comments:

baskeddy said...

Thanks for sharing, but I couldn't get the code to work unless I changed the port to 80 in the socket.connect()

From:
s.connect(('google.com', 0))

to:

s.connect(('google.com', 80))

Erik said...

thx baskeddy