python獲取本機局域網IP地址(適用於Windows、Linux、Mac)


 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"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM