python获取本地ip地址的方法

''' The Method for getting Local Host IP address under the Linux. '''
# Uses the Linux SIOCGIFADDR ioctl to find the IP address associated with a network interface,
# given the name of that interface, e.g. “eth0”.
# The address is returned as a string containing a dotted quad.
def getLocalHost(if_name='eth0'):
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  return socket.inet_ntoa(fcntl.ioctl(
      s.fileno(),
      0x8915, # SIOCGIFADDR
      struct.pack('256s', if_name[:15])
      )[20:24])

posted @ 2015-01-13 13:57  AndyRobb  阅读(247)  评论(0编辑  收藏  举报