Get public IP in Python
In today’s world, being able to access the internet is a necessity. One of the first things that happens when you connect to the internet is that your device is assigned an IP address. This IP address is used to identify your device on the internet. Sometimes you might need to know your public IP address, which is the IP address that is visible to the outside world. In this blog post, we will discuss how to use Python socket to get your public IP address.
Example 1
import socket
port = 80
host = "www.google.com"
print("Creating socket...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected from", s.getsockname())
print("Connected to", s.getpeername())
Let’s break down the code to understand how it works.
- First, we import the socket module.
- Then, we define a function named
get_public_ip()that creates a socket object using theAF_INETaddress family andSOCK_DGRAMsocket type. - Next, we connect the socket to Google’s DNS server using the
connect()method and passing in the IP address and port number. - Finally, we use the
getsockname()method to get the local IP address of the socket, which is our public IP address. - The
getsocketname()method can be used to return the local IP address and port number, whilegetpeername()can be used to return the server’s IP address and port number.
Example 2
or use UDP to connect
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
Example 3
or running in shell
alias myip="python3 -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"
myip
Some of the content is generated by AI, please be cautious in identifying it.