Skip to content

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.

Example 1

import socket

port = 80
host = ""
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_INET address family and SOCK_DGRAM socket 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, while getpeername() 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(("", 80))

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((\"\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"


Back to Table of Contents

  1. License under CC BY-NC 4.0
  2. Copyright issue feedback, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected.