Get IP address in Python
Method 1: Using socket.gethostbyname
The gethostbyname function retrieves host information corresponding to a hostname from a host database.
Python3
import socket print (socket.gethostbyname(socket.gethostname())) |
Output:
10.143.90.178
Method 2: Using socket.socket instance
Here, two parameters were supplied to a socket instance that was created. AF INET is the first parameter, while SOCK STREAM is the second. AF INET stands for ipv4 address-family. The connection-oriented TCP protocol is referred to as SOCK STREAM.
Python3
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # connect() for UDP doesn't send packets s.connect(( '10.0.0.0' , 0 )) print (s.getsockname()[ 0 ]) |
Output:
10.143.90.178
Display Hostname and IP address in Python
There are many ways to find the hostname and IP address of a local machine. Here is a simple method to find the hostname and IP address using python code.
Library used – socket: This module provides access to the BSD socket interface. It is available on all modern Unix systems, Windows, macOS, and probably additional platforms in Python.