Finding local IP addresses using Python's stdlib
import socket
socket.gethostbyname(socket.gethostname())
This won't work always (returns 127.0.0.1
on machines having the hostname in /etc/hosts
as 127.0.0.1
), a paliative would be what gimel shows, use socket.getfqdn()
instead. Of course your machine needs a resolvable hostname.
How to get local ip address python?
You can use this code:
import socket
hostname = socket.getfqdn()
print("IP Address:",socket.gethostbyname_ex(hostname)[2][1])
or this to get public ip:
import requests
import json
print(json.loads(requests.get("https://ip.seeip.org/jsonip?").text)["ip"])
Finding local IP addresses using Python's stdlib
import socket
socket.gethostbyname(socket.gethostname())
This won't work always (returns 127.0.0.1
on machines having the hostname in /etc/hosts
as 127.0.0.1
), a paliative would be what gimel shows, use socket.getfqdn()
instead. Of course your machine needs a resolvable hostname.
Python - Get localhost IP
I generally use this code:
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
ifname[:15]))[20:24])
def get_lan_ip():
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith("127.") and os.name != "nt":
interfaces = [
"eth0",
"eth1",
"eth2",
"wlan0",
"wlan1",
"wifi0",
"ath0",
"ath1",
"ppp0",
]
for ifname in interfaces:
try:
ip = get_interface_ip(ifname)
break
except IOError:
pass
return ip
I don't know it's origin, but it works on Linux/Windows.
Edit:
This code is used by smerlin in this stackoverflow question.
How can I get the IP address from a NIC (network interface controller) in Python?
Two methods:
Method #1 (use external package)
You need to ask for the IP address that is bound to your eth0
interface. This is available from the netifaces package
import netifaces as ni
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print(ip) # should print "192.168.100.37"
You can also get a list of all available interfaces via
ni.interfaces()
Method #2 (no external package)
Here's a way to get the IP address without using a python package:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('eth0') # '192.168.0.110'
Note: detecting the IP address to determine what environment you are using is quite a hack. Almost all frameworks provide a very simple way to set/modify an environment variable to indicate the current environment. Try and take a look at your documentation for this. It should be as simple as doing
if app.config['ENV'] == 'production':
# send production email
else:
# send development email
How do I get my local ip address from a python script on linux?
You can use an external package, for example netifaces, or you can look for the ipaddress of a given interface, specified by its name. Take a look at this question.
Getting all IP addresses connected to WiFi using python and scapy
Forgive me if I'm misunderstanding your question.. what you're trying to do is map all live hosts on your LAN?
A simpler approach is to use the builtin ipaddress
and socket
libraries. For each IP in your LAN subnet, try connecting a socket to various ports (TCP/UDP). If a connection is established, a host exists at that IP.
Here's some code I can think of that might solve your problem (I have not tested this myself)
import socket
import ipaddress
live_hosts = []
# google popular tcp/udp ports and add more port numbers to your liking
common_tcp_ports = [23, 80, 443, 445]
common_udp_ports = [67, 68, 69]
def scan_subnet_for_hosts(subn = '192.168.1.0/24'):
network = ipaddress.IPv4Network(subn)
for ipaddr in list(network.hosts()):
for port in common_tcp_ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
s.connect((str(ipaddr), port))
live_hosts.append(ipaddr)
except socket.error:
continue
for port in common_udp_ports:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# UDP is connectionless, so you might have to try using s.send() as well
s.connect((str(ipaddr), port))
live_hosts.append(ipaddr)
except socket.error:
continue
scan_subnet_for_hosts()
for host in live_hosts:
print(f"Found live host: {str(host)}")
Related Topics
How to Modify List Entries During For Loop
How to Sort a List of Objects Based on an Attribute of the Objects
"Inconsistent Use of Tabs and Spaces in Indentation"
How to Convert All Strings in a List of Lists to Integers
Finding the Source Code For Built-In Python Functions
Error Message: "'Chromedriver' Executable Needs to Be Available in the Path"
Removing from a List While Iterating Over It
How to Install Pip on Macos or Os X
Maximum and Minimum Values For Ints
How to Split a List Based on a Condition
Pip Install Failing With: Oserror: [Errno 13] Permission Denied on Directory
Wait Until Page Is Loaded With Selenium Webdriver For Python
Unicodeencodeerror: 'Charmap' Codec Can't Encode Characters