Skip to content

Instantly share code, notes, and snippets.

@ZacBlanco
Created November 21, 2016 05:08
Show Gist options
  • Save ZacBlanco/520abe05d18033e0d5b920a952bf7856 to your computer and use it in GitHub Desktop.
Save ZacBlanco/520abe05d18033e0d5b920a952bf7856 to your computer and use it in GitHub Desktop.
Get IP address of network interface
import socket
import fcntl
import struct
import sys
def get_ip_address(ifname):
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])
# print(get_ip_address('eth0')) # '192.168.0.110'
if __name__ == "__main__":
print(get_ip_address(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment