您的位置:首页 > 编程语言 > Python开发

python获取本地ip地址的方法

2015-01-13 13:57 716 查看
''' 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])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: