Created
September 7, 2018 20:38
-
-
Save socketz/fc9bbbba7be561852ae8905e277402b8 to your computer and use it in GitHub Desktop.
Python3 get interface IP address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import socket | |
import fcntl | |
import struct | |
def get_ip_address(ifname): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
fdsock = s.fileno() | |
SIOCGIFADDR = 0x8915 | |
ifreq = struct.pack('16sH14s', bytes(ifname, 'utf-8'), socket.AF_INET, bytes('\x00'*14, 'utf-8')) | |
try: | |
res = fcntl.ioctl(fdsock, SIOCGIFADDR, ifreq) | |
except: | |
return None | |
ip = struct.unpack('16sH2x4s8x', res)[2] | |
return socket.inet_ntoa(ip) | |
print(get_ip_address('eth0')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment