为什么python的套接字.getfqdn()返回localhost.localdomain有时候?

2024-10-05 22:52:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我不太明白我在主机上使用socket.getfqdn()时看到的是什么。下面是我看到的,然后我来解释一下:

[root@myawesomehost.iscool ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
[root@myawesomehost.iscool ~]#
[root@myawesomehost.iscool ~]#
[root@myawesomehost.iscool ~]# python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import socket
>>> socket.getfqdn()
'myawesomehost.iscool.ny.domain.com'
>>> socket.gethostname()
'myawesomehost.iscool.ny.domain.com'
>>>
[1]+  Stopped                 python
[root@myawesomehost.iscool ~]# vim /etc/hosts
[root@myawesomehost.iscool ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4 myawesomehost.iscool.ny.domain.com
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6 myawesomehost.iscool.ny.domain.com
[root@myawesomehost.iscool ~]#
[root@myawesomehost.iscool ~]#
[root@myawesomehost.iscool ~]# fg
python

>>> socket.getfqdn()
'localhost.localdomain'
>>> socket.gethostname()
'myawesomehost.iscool.ny.domain.com'
>>>
>>>
>>> exit()

因此,当我将主机的fqdn附加到/etc/hosts127.0.0.1项的末尾时,socket.getfqdn()开始返回{}。但是,如果我删除它,一切正常,它返回正确的fqdn。在

我阅读了pythonsocket文档(https://docs.python.org/2/library/socket.html#socket.getfqdn),其中介绍了如何选择带有句点的第一个值。但是为什么它不总是重复呢?在

基本上,我想我已经把我的问题缩小到这一个可重复的步骤。但我不知道引擎盖下发生了什么,我真的很想知道。在


Tags: comlocalhostdomainetcrootsocketcathosts
1条回答
网友
1楼 · 发布于 2024-10-05 22:52:44

医生说:

Return a fully qualified domain name for name. If name is omitted or empty, it is interpreted as the local host.

我敢肯定你知道一个主机可以有多个接口,每个接口可能有自己的IP地址(甚至几个),IP地址可以解析为一个FQDN。在

因此,除了localhost之外,还有一个主机的通用规范FQDN。如果它有一个命名的条目(我想应该是这样的),则返回后者。在

对于特定的IP,请尝试使用.getfqdn(),或者考虑使用^{}并从它返回的列表中提取正确的别名。在

我还认为这与Python无关;这是IP栈的工作原理。在

相关问题 更多 >