Search code snippets, questions, articles...

How to Get IP Addresses in Python - A Quick Tutorial

If you're looking for a quick tutorial on how to get IP addresses in Python, you've come to the right place. In this article, we'll show you how to use the Python socket module to get IP addresses. We'll also show you how to use the Python IP address module to validate IP addresses.
import socket

host_name = socket.gethostname()
client_ip = socket.gethostbyname(host_name)

print("Host name is: {}".format(host_name))
print("Client IP Address: {}".format(client_ip))
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

Host name is: Host name
Client IP Address: 127.0.0.1

The code example imports the socket module. The socket module provides access to the BSD socket interface. The host_name variable is assigned the value returned by the socket.gethostname() function. The client_ip variable is assigned the value returned by the socket.gethostbyname() function. The host_name and client_ip variables are then printed to the console.

Another example to get the client IP in python using the socket module:

import socket

client_ip = socket.gethostbyname(socket.gethostname())

print("Client IP Address: {}".format(client_ip))

The code example above is using the socket module to get the client's IP address. The socket.gethostbyname() function will return the IP address of the given hostname (in this case, the client's hostname). The socket.gethostname() function will return the client's hostname. The client_ip variable will contain the client's IP address. The code will then print out the client's IP address.

Was this helpful?
0 Comments