Created
June 6, 2013 17:17
-
-
Save combatpoodle/5723198 to your computer and use it in GitHub Desktop.
Function to reliably retrieve a local IP address on OS X + Linux in Python. Interface specification only works on Linux.
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
# get_ip is from http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib, added a fallback to making a connection for OS X/local testing | |
def get_ip(iface = 'eth0'): | |
import socket, struct, fcntl | |
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
sockfd = sock.fileno() | |
SIOCGIFADDR = 0x8915 | |
ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14) | |
try: | |
res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq) | |
except: | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.connect(("gmail.com",80)) | |
ip = s.getsockname()[0] | |
s.close() | |
return ip | |
ip = struct.unpack('16sH2x4s8x', res)[2] | |
return socket.inet_ntoa(ip) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment