2022年 11月 7日

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'
>>>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

方法二

>>> 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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

方法三

>>> 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']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15