Last active
January 3, 2016 07:09
-
-
Save martijnvandijk/8427116 to your computer and use it in GitHub Desktop.
Get the ip address from a given interface
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
# 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