. Advertisement .
..3..
. Advertisement .
..4..
Your laptop, tablet, and mobile always have their IP address. This Internet Protocol is unique to your network hardware, where it connects your device with others on your network and all over the world.
So how to get python IP address? This article will help you find your IP address using Python.
How To Get Python IP Address
There are three ways to get your IP address by Python functions:
Method 1: Import The Socket Library
The Python socket module is a common function to get your device’s IP address. It can allow users to create new network connections while transmitting messages throughout the system.
The gethostname() is built to return the hostname of the device, under which the function executes Python.
Code:
import socket
h_name = socket.gethostname()
IP_addres = socket.gethostbyname(h_name)
print("Host Name is:" + h_name)
print("Computer IP Address is:" + IP_addres)
Output:
Host Name is: DESKTOP-AJNOCQ
Computer IP Address is: 192.168.45.161
Method 2: Use The socket.getsockname() Function
This method is restricted to those devices with an Internet-connected route. Follow the codes, and it will return your tuple port with an IP address.
Code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
Output:
192.168.0.112
You can also exploit it to get a user-defined one that requires no routable internet access.
Code:
import socket
def extract_ip():
st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
st.connect(('10.255.255.255', 1))
IP = st.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
st.close()
return IP
print(extract_ip())
Output:
192.168.0.112
Method 3: Employ netifaces Module
As its name suggests, Netifaces is often used to offer users information about the status of your network interfaces.
Code:
from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
print(' '.join(addresses))
Output:
No IP addr
No IP addr
No IP addr
No IP addr
192.168.0.104
127.0.0.1
How To Check IP Address Validation By Python
The socket and inet_aton() functions help you check whether your IP address is valid or not.
Code:
import socket
IP = '127.0.0.2561'
try:
socket.inet_aton(IP)
print("Valid IP address")
except socket.error:
print("Invalid IP")
You will receive two results. The first one is “ Invalid IP address,” You get the except block executed. On the other hand, if the given IP address is valid, the returned result will be valid.
Conclusion
How to get Python IP address? There are three ways to answer this question. Python will offer you three common functions: easy to code, test, and give back a correct result.
Leave a comment