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 to get Network Interface Card names in Python?
I don't think there's anything in the standard library to query these names.
If I needed these names on a Linux system I would parse the output of ifconfig
or the contents of /proc/net/dev
. Look at this blog entry for a similar problem.
How to get the physical interface IP address from an interface
You should use netifaces. It is designed to be cross-platform and contains specialised code for Windows together with a variety of generic versions that work on different UNIX/UNIX-like platforms.
As of netifaces version 0.10.0, Python3 is supported.
Usage Summary
>>> from netifaces import AF_INET, AF_INET6, AF_LINK, AF_PACKET, AF_BRIDGE
>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>>
>>> ni.ifaddresses('eth0')[AF_LINK] # NOTE: AF_LINK is an alias for AF_PACKET
[{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}]
>>> ni.ifaddresses('eth0')[AF_INET]
[{'broadcast': '172.16.161.7', 'netmask': '255.255.255.248', 'addr': '172.16.161.6'}]
>>>
>>> # eth0 ipv4 interface address
>>> ni.ifaddresses('eth0')[AF_INET][0]['addr']
'172.16.161.6'
>>>>
Details
Windows Support:
No compiler required for most MS Windows installs. If you get warnings about installing MS Visual C++ for Windows, be very careful because you need to match the version of compiler used for your python with that used for the module.
Detailed example of netifaces data structures:
>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>> ni.ifaddresses('eth0')
{
17: [
{
'broadcast': 'ff:ff:ff:ff:ff:ff',
'addr': '00:02:55:7b:b2:f6'
}
],
2: [
{
'broadcast': '172.16.161.7',
'netmask': '255.255.255.248',
'addr': '172.16.161.6'
}
],
10: [
{
'netmask': 'ffff:ffff:ffff:ffff::',
'addr': 'fe80::202:55ff:fe7b:b2f6%eth0'
}
]
}
>>>
>>> print(ni.ifaddresses.__doc__)
Obtain information about the specified network interface.
Returns a dict whose keys are equal to the address family constants,
e.g. netifaces.AF_INET, and whose values are a list of addresses in
that family that are attached to the network interface.
>>>
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'172.16.161.6'
The numbers used to index protocols are from /usr/include/linux/socket.h
(in Linux)... EDIT: my 3.2 kernel has them here: /usr/src/linux-headers-3.2.0-4-common/include/linux/socket.h
#define AF_INET 2 /* Internet IP Protocol */
#define AF_INET6 10 /* IP version 6 */
#define AF_PACKET 17 /* Packet family */
The good news is that you don't have to remember all those header constants, they are included with netifaces:
>>> from netifaces import AF_INET, AF_INET6, AF_LINK, AF_PACKET, AF_BRIDGE
>>> import netifaces as ni
Python, How to get all external ip addresses with multiple NICs
You should use netifaces. It is designed to be cross-platform on Mac OS X, Linux, and Windows.
>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>> ni.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}], 2: [{'broadcast': '24.19.161.7', 'netmask': '255.255.255.248', 'addr': '24.19.161.6'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::202:55ff:fe7b:b2f6%eth0'}]}
>>>
>>> ni.ifaddresses.__doc__
'Obtain information about the specified network interface.\n\nReturns a dict whose keys are equal to the address family constants,\ne.g. netifaces.AF_INET, and whose values are a list of addresses in\nthat family that are attached to the network interface.'
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'24.19.161.6'
The numbers used to index protocols are from /usr/include/linux/socket.h
(in Linux)...
#define AF_INET 2 /* Internet IP Protocol */
#define AF_INET6 10 /* IP version 6 */
#define AF_PACKET 17 /* Packet family */
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.
bind/connect to network interface card using python
Actually the answer is very simple. And its similar to what Idx did in the previous answer:
def findConnectedRobot():
'''
Finds which robots are connected to the computer and returns the
addresses of the NIC they are connected to
'''
robot_address = [] # stores NIC address
import netifaces
# get the list of availble NIC's
for card in netifaces.interfaces():
try:
# get all NIC addresses
temp = netifaces.ifaddresses(\
card)[netifaces.AF_INET][0]['addr']
temp2 = temp.split('.')
# see if address matches common address given to NIC when
# NIC is connected to a robot
if temp2[0] == '192' and int(temp2[3]) < 30:
print('appending address: ' + temp)
robot_address.append(temp)
except BaseException:
pass
return robot_address
After I get the "robot addresses" then I can just bind/connected to them like a normal socket.
Thanks for the help!
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.
Related Topics
Scraping Dynamic Content Using Python-Scrapy
Tkinter Gui Layout Using Frames and Grid
Replacing Column Values in a Pandas Dataframe
Function for Factorial in Python
How to Put Individual Tags for a Matplotlib Scatter Plot
How to Forward-Declare a Function to Avoid 'Nameerror's for Functions Defined Later
Why Does '.Sort()' Cause the List to Be 'None' in Python
JSONify a SQLalchemy Result Set in Flask
How to Upload File ( Picture ) with Selenium, Python
How to Overload _Init_ Method Based on Argument Type
Extract Images from PDF Without Resampling, in Python
Why am I Getting Attributeerror: Object Has No Attribute
Difference Between Filter and Filter_By in SQLalchemy
Replacing Few Values in a Pandas Dataframe Column with Another Value
How Could I Use Requests in Asyncio
How to Expand a List to Function Arguments in Python
Cartesian Product of Two Lists in Python
Python3: Importerror: No Module Named '_Ctypes' When Using Value from Module Multiprocessing