Skip to content

Instantly share code, notes, and snippets.

@jedy
Created June 5, 2012 09:55
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 jedy/2874073 to your computer and use it in GitHub Desktop.
Save jedy/2874073 to your computer and use it in GitHub Desktop.
get ip address
import socket
import fcntl
import struct
def get_ip_address(ifname):
"""
>>> get_ip_address('lo')
'127.0.0.1'
>>> get_ip_address('eth0')
'38.113.228.130'
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment