python获取主机名和IP地址

原文链接:https://blog.csdn.net/Jerry_1126/article/details/85482905

方法一

>>> import socket
>>> # 获取主机名
>>> hostname = socket.gethostname()
>>> hostname
'USER-20150331GI'
>>>
>>> # 获取IP地址
>>> ip = socket.gethostbyname(hostname)
>>> ip
'192.168.1.3'
>>>

方法二

>>> 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']
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页