我正在为本地网络写一个聊天程序。我希望能够识别计算机,并获得用户设置的计算机名称与Python。


当前回答

你必须执行这行代码

sock_name = socket.gethostname()

然后你可以使用名称来查找地址:

print(socket.gethostbyname(sock_name))

其他回答

os.getenv('HOSTNAME')和os.getenv。environ['HOSTNAME']并不总是有效。在cron作业和WSDL中,没有设置HTTP HOSTNAME。用这个代替:

import socket
socket.gethostbyaddr(socket.gethostname())[0]

它总是(即使在Windows上)返回一个完全限定的主机名,即使你在/etc/hosts中定义了一个短别名

如果你在/etc/hosts中定义了一个别名,那么socket.gethostname()将返回该别名。Platform.uname()[1]做同样的事情。

我遇到了一个上述方法不起作用的案例。这是我现在使用的:

import socket
if socket.gethostname().find('.')>=0:
    name=socket.gethostname()
else:
    name=socket.gethostbyaddr(socket.gethostname())[0]

它首先调用gethostname,看看它是否返回类似主机名的东西,如果不是,它就使用我原来的解决方案。

在某些系统上,主机名是在环境中设置的。如果是这样的话,操作系统模块可以通过os.getenv把它从环境中拉出来。例如,如果HOSTNAME是包含你想要的内容的环境变量,下面将得到它:

import os
system_name = os.getenv('HOSTNAME')

Update: As noted in the comments, this doesn't always work, as not everyone's environment is set up this way. I believe that at the time I initially answered this I was using this solution as it was the first thing I'd found in a web search and it worked for me at the time. Due to the lack of portability I probably wouldn't use this now. However, I am leaving this answer for reference purposes. FWIW, it does eliminate the need for other imports if your environment has the system name and you are already importing the os module. Test it - if it doesn't work in all the environments in which you expect your program to operate, use one of the other solutions provided.

从至少python >= 3.3:

你可以使用字段nodename,避免使用数组索引:

os.uname().nodename

虽然,甚至os的文档。Uname建议使用socket.gethostname()

你必须执行这行代码

sock_name = socket.gethostname()

然后你可以使用名称来查找地址:

print(socket.gethostbyname(sock_name))

你可能会加载操作系统模块,所以另一个建议是:

import os
myhost = os.uname()[1]