Dud :
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?
Tylerr :
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
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=220619&siteId=1