Python get hostname and IP address

Original link: https://blog.csdn.net/Jerry_1126/article/details/85482905

method one

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

Method Two

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

Method Three

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

Guess you like

Origin blog.csdn.net/Free_time_/article/details/107998335