Skip to content

Instantly share code, notes, and snippets.

@ourway
Created April 13, 2015 12:59
Show Gist options
  • Save ourway/f1c5e8a7f1464e460fa6 to your computer and use it in GitHub Desktop.
Save ourway/f1c5e8a7f1464e460fa6 to your computer and use it in GitHub Desktop.
Get Server IP in unix system via python
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)
get_ip('eth0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment