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

【原创】Python 获取本机内网…

2017-03-20 14:43 351 查看
Python - Get localhost IP,Linux和Windows通用。

代码:

---------------------------------------------------------------------------------

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import socket

#nt -- > windows
if os.name != "nt":
    import fcntl
    import struct

    def
get_interface_ip(ifname):
     
  s = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM)
     
  return socket.inet_ntoa(fcntl.ioctl(s.fileno(),
0x8915, struct.pack('256s',
     
     
     
     
     
  ifname[:15]))[20:24])

def get_lan_ip():
    ip =
socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.")
and os.name != "nt":
     
  interfaces = [
     
     
"eth0",
     
     
"eth1",
     
     
"eth2",
     
     
"wlan0",
     
     
"wlan1",
     
     
"wifi0",
     
     
"ath0",
     
     
"ath1",
     
     
"ppp0",
     
      ]
     
  for ifname in interfaces:
     
      try:
     
     
    ip =
get_interface_ip(ifname)
     
     
    break
     
      except
IOError:
     
     
    pass
    return ip

if __name__ == '__main__'
    print get_lan_ip()
---------------------------------------------------------------------------------

参考网址:
如何用Python获取本机ip
使用Python获得本机IP地址》#这种东西太让人觉得恶心...无聊
Python - Get localhost IP [duplicate]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: