8

需要说明的是:我两周前刚开始使用 Python,但我是一名 C#、ASP、PHP、JavaScript 开发人员。

我刚刚使用 Python 和 PyQt 开始了一个新项目,我希望我的项目成为一个能够与其他计算机上的该服务器的其他实例通信的服务器。

所以,我需要获取计算机的 IP 地址和主机名。

首先,我考虑过使用 MSDOS 的“net view”命令,但这是在我的工作中尝试这个命令之前,发现这可能需要大约 15 秒(我认为这太慢了)。

我有这个想法来自:https ://stackoverflow.com/a/15497083/1598891

此外,“net view”命令可以返回不再在网络上的计算机,并在尝试通过主机名获取其 IP 地址时导致异常(这也会在每次无法访问计算机时减慢进程)。

我的问题:有没有办法让本地网络上的所有计算机 IP 和主机名不经过net viewWindows,因为这net view可能是一个缓慢的操作?

另外,有没有办法只获取运行我的应用程序的计算机?(所以会更快)

提前致谢

4

2 回答 2

23

对于 localhost 的主机名和 ip,您可以使用套接字模块和 gethostname 以及 gethostbyname 方法:

import socket

hostname = socket.gethostname()
IP = socket.gethostbyname(hostname)
于 2013-10-28T15:02:57.850 回答
5

If you want to get the IP address of the host on which the python script is running, then the answer provided by user2096338 is the way to go.

In order to discover all the computers on a network within a LAN you can use scapy. https://github.com/bwaldvogel/neighbourhood/blob/master/neighbourhood.py is a link that I found while browsing a similar SO question; which discovers all computers within a network (LAN).

If you want to ensure that the above script returns only those computers that are running your server - then there are multiple ways to do so, listed below in order of portablility

  1. Whenever you install your server on a host, then register itself into a central database which can then be queried by a new instance of your service to identify all computers where the peer servers are running
  2. Use WMI (since you are on Windows) to query all processes running on the peer system anc check if your server process is one amongst them.
  3. Your server will keep a probing port open and a new server installation will ping to the server on this probing port for each of the hosts in the network. If it gets a response, then this computer is running the server process.

In my opinion, method 1 is the safest and portable, since it prevents the opening up of unnecessary ports( like method 3) which are security holes (depending on whose context your python script runs). It also does not depend on the availability of the WMI service on the remote hosts ( some systems may have WMI disabled).

Hope this helps

于 2013-10-28T15:41:39.360 回答