Quantcast
Channel: Coder's Talk
Viewing all articles
Browse latest Browse all 40

Python Code to Get IP Address From Interface Name

$
0
0

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!

Viewing all articles
Browse latest Browse all 40

Trending Articles