Skip to content

Instantly share code, notes, and snippets.

@martijnvandijk martijnvandijk/getip.py
Last active Jan 3, 2016

Embed
What would you like to do?
Get the ip address from a given interface
# All credit goes to StackOverflow user tMC
# from http://stackoverflow.com/a/9267833
import socket, struct, fcntl
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockfd = sock.fileno()
SIOCGIFADDR = 0x8915
def get_ip(iface = 'eth0'):
ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
try:
res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
except:
return None
ip = struct.unpack('16sH2x4s8x', res)[2]
return socket.inet_ntoa(ip)
print get_ip('eth0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.