Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get global ip address in python?

Tags:

python

I am converting bash code to python code. I got a global ip address of the own host in bash code by

hostname -I  # output -> 19x.xxx.xxx.xxx xxxx:xxxx:....

The 19x.xxx.xxx.xxx is the global ip address of the own host.

I tried to get the global ip address in python by

import socket
name=socket.gethostname()
id_address=socket.gethostbyname(name)
print("id_address = {0}".format(id_address))

The output was the local host address like

127.xxx.xxx.xxx

Do I have a way to get a global ip address in python?

like image 268
mora Avatar asked Oct 17 '25 06:10

mora


1 Answers

You can do it without any external libraries:

import urllib.request

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

print(external_ip)

This uses a website that gives you your public ipv4 address using only the standard library, which is great.

Code is tested on python3.

Similar question: Getting a machine's external IP address with Python

Similar answer: https://stackoverflow.com/a/41432835/14154066

like image 198
איתן טורפז Avatar answered Oct 19 '25 20:10

איתן טורפז



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!