Skip to content

Instantly share code, notes, and snippets.

@martijnvandijk
Last active January 3, 2016 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martijnvandijk/8427116 to your computer and use it in GitHub Desktop.
Save martijnvandijk/8427116 to your computer and use it in GitHub Desktop.
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