菜鸟笔记
提升您的技术认知

用python获取本地主机名及ip地址的简单方式-ag真人游戏

方法一:

>>> 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']

 

网站地图