In this article, you will learn how to get the IPv4 IP address of the local machine in python. There are various ways to find the IPv4 IP address of the local machine in Python.
Here are some examples to get the IPv4 IP address of the local machine in python.
In this example, first, you need to import the socket module from the Python Standard Library and use the socket.gethostname()
method to find the hostname and socket.gethostbyname()
method to get the IPv4 IP address of a computer.
Here is the source code of the program to find the Hostname and the IPv4 IP address of the local computer in python.
# To get the IPv4 IP address of the local machine in Python
# importing socket module
import socket
# getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
# getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# printing the hostname and ip_address
print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
In this example, we used the socket
module and socket.socket()
and connect()
and socket.getsockname()
Method to get the IPv4 IP address of the local machine in python.
Here is the source code of another approach to get the IPv4 IP address of the local machine in python.
# To get the IPv4 IP address of the local machine using
# Using socket module and socket.socket() and connect()
# and socket.getsockname() Method in Python
# Import Module
import socket
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# connect to the server on local computer
s.connect(("8.8.8.8", 80))
# Print Output
print("HostName: ",s.getsockname()[0])
s.close()
In this example, we used the socket
module and socket.socket()
and connect()
and socket.getsockname()
Method to get the IPv4 IP address of the local machine in python.
Here is the source code of another approach to get the IPv4 IP address of a local machine in python.
# To get the IPv4 IP address of the local machine using
# Using socket module and socket.socket(), setsockopt(), connect()
# and socket.getsockname() Method in Python
# Import Module
import socket
# Define a Function
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect(('', 0))
return s.getsockname()[0]
# Print the Output
print ("HostName: ",getNetworkIp())
I hope this article will help you to understand how to get the IPv4 IP address of the local machine in python.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments