'How to get global ip address in 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?



Solution 1:[1]

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

Solution 2:[2]

You have to use a computer/server on the internet to give this information to you. Your own computer can only give you the network card's IP address on the local network, e.g. something like 192.16.8..

You can use the whatismyip module to get your external, public IP address. It has no dependencies outside the Python 3 standard library. It connects to public STUN servers and what-is-my-ip websites to find the IPv4 or IPv6 address. Run pip install whatismyip

Example:

>>> import whatismyip
>>> whatismyip.amionline()
True
>>> whatismyip.whatismyip()  # Prefers IPv4 addresses, but can return either IPv4 or IPv6.
'69.89.31.226'
>>> whatismyip.whatismyipv4()
'69.89.31.226'
>>> whatismyip.whatismyipv6()
'2345:0425:2CA1:0000:0000:0567:5673:23b5'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thisisrandy
Solution 2 Al Sweigart