Skip to content

Instantly share code, notes, and snippets.

@socketz
Created September 7, 2018 20:38
Show Gist options
  • Save socketz/fc9bbbba7be561852ae8905e277402b8 to your computer and use it in GitHub Desktop.
Save socketz/fc9bbbba7be561852ae8905e277402b8 to your computer and use it in GitHub Desktop.
Python3 get interface IP address
#!/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