Python 获取本地主机 hostname 很简单,一行代码就能搞定。获取 IP 地址也一样简单,下面分享一下这些方法。都很简单,基本都是通过 Python 的 socket 库来进行获取的。Python socket 还是一个非常强大的网络功能库,很多时候配合 socketserver 使用效果更好。
一、推荐方法
>>> import socket >>> # 获取主机名 >>> hostname = socket.gethostname() >>> hostname 'USER-20150331GI' >>> >>> # 获取IP地址 >>> ip = socket.gethostbyname(hostname) >>> ip '192.168.1.3'
对于获取 IP 地址,其实 socket.gethostbyname() 很多情况下并不能准确获取到 IP 地址,很多时候会返回一个 127.0.0.1 或者是私有 IP,下面的方法可以更准确的获取 IP 地址(也就是下方的备用方法一):
import socket
def get_host_ip():
"""
查询本机ip地址
:return: ip
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
if __name__ == '__main__':
print(get_host_ip())
二、备用方法
备用方法一:
>>> import socket
>>> # 获取主机名
>>> hostname = socket.getfqdn(socket.gethostname())
>>> hostname
'USER-20150331GI'
>>>
>>> # 获取IP地址
>>> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>>> s.connect(('8.8.8.8', 80))
>>> ip = s.getsockname()[0]
>>> ip
'192.168.1.3'
备用方法二:
>>> import socket
>>> hostname = socket.gethostname()
>>> ip_lists = socket.gethostbyname_ex(hostname)
>>> ip_lists
('USER-20150331GI', [], ['192.168.1.3'])
>>>
>>> # 获取主机名
>>> hostname = ip_lists[0]
>>> hostname
'USER-20150331GI'
>>>
>>> # 获取IP地址
>>> ip = lst[-1]
>>> ip
['192.168.1.3']
参考文献:

老唐笔记















