Python Code to Get IP Address From Interface Name


From my previous code on How To Print Active Network Interface List in Linux using Python, I got this question.

Question from jimchris:
Nice work, now how do we get ip address from ifacedata?

My Answer:
Here's how... Add this function to your python code:
def getifip(ifn):
    import socketfcntlstruct
    sck socket.socket(socket.AF_INETsocket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(sck.fileno(),0x8915,struct.pack('256s'ifn[:15]))[20:24])

Then use it in your previous code like this:
print getifip(ifacedata[0])

Update: you can also download the python source code here

Wish you luck and Happy Coding!

Comments

Umar said…
with these:

#!/usr/bin/python

# read the file /proc/net/dev
f = open('/proc/net/dev','r')

# put the content to list
ifacelist = f.read().split('\n')

# close the file
f.close()

# remove 2 lines header
ifacelist.pop(0)
ifacelist.pop(0)

# loop to check each line
for line in ifacelist:

ifacedata = line.replace(' ','').split(':')

# check the data have 2 elements
if len(ifacedata) == 2:

# check the interface is up (Transmit/Receive data)
if int(ifacedata[1]) > 0:

# print the interface
print ifacedata[0]

def getifip(ifn):
import socket, fcntl, struct
sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(sck.fileno(),0x8915,struct.pack('256s', ifn[:15]))[20:24])

print getifip(ifacedata[0])

i got these:

lo
eth0
vmnet1
vmnet8
Traceback (most recent call last):
File "iface.py", line 36, in
print getifip(ifacedata[0])
File "iface.py", line 34, in getifip
return socket.inet_ntoa(fcntl.ioctl(sck.fileno(),0x8915,struct.pack('256s', ifn[:15]))[20:24])
ApOgEE said…
I couldn't see your code properly since python rely on code indentation too and this comment area won't allow <pre> tags.

Please download my sample source code (updated on the post) and see the diff. It works fine on my PC.

Popular posts from this blog

How to Create Hyperlink on Blogger Post

How to Add a Sudo User on AlmaLinux 9.2 (Turquoise Kodkod): A Step-by-Step Guide

How to Show and Hide Text in Blog Post