Using Python socket to get public address
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.
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())
Understanding the Code
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 the
AF_INETaddress family and
- 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.
getsocketname()method can be used to return the local IP address and port number, while
getpeername()can be used to return the server’s IP address and port number.
or use UDP to connect
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("220.127.116.11", 80)) print(s.getsockname()) s.close()
or running in shell
alias myip="python3 -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname()) if not ip.startswith(\"127.\")][:1], [[(s.connect((\"18.104.22.168\", 53)), s.getsockname(), s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]]]) if l])'" myip
Back to Table of Contents
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.com, replace # with @
- Not all the commands and scripts are tested in production environment, use at your own risk
- No personal information is collected.