python获取本机局域网IP地址(适用于Windows、Linux、Mac)

时间:2024-02-21 10:06:30
 1 import socket
 2 import platform
 4 
 5 def getip():
 6     try:
 7         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 8         s.connect((\'www.baidu.com\', 0))
 9         ip = s.getsockname()[0]
10     except:
11         ip = "x.x.x.x"
12     finally:
13         s.close()
14     return ip
15 
16 if __name__ == "__main__":
17     ip_address = "0.0.0.0"
18     sysstr = platform.system()
19     if sysstr == "Windows":
20         ip_address = socket.gethostbyname(socket.gethostname())
21         print "Windows @ " + ip_address
22     elif sysstr == "Linux":
23         ip_address = getip()
24         print "Linux @ " + ip_address
25     elif sysstr == "Darwin":
26         ip_address = socket.gethostbyname(socket.gethostname())
27         print "Mac @ " + ip_address
28     else:
29         print "Other System @ some ip"