使用 Python 检查来自 IP 地址的网络连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16808721/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check network connection from an IP address with Python
提问by Nethan
How can I check if there is still connection from a specific ip address using python.
如何使用 python 检查来自特定 IP 地址的连接是否仍然存在。
回答by Netorica
ping the ip address
ping ip地址
import os
#192.168.1.10 is the ip address
ret = os.system("ping -o -c 3 -W 3000 192.168.1.10")
if ret != 0:
    print "pc still alive"
well in any case you really want to check for availability of incoming connection on the PC you are trying to connect you need to make a program that will receive the connection which is already out of the question.
无论如何,您真的想检查您尝试连接的 PC 上传入连接的可用性,您需要制作一个程序来接收已经不可能的连接。
回答by suspectus
import os
address = "my_ip_address"
os.system('ping ' + address)
回答by kadi
You can use socket library:
您可以使用套接字库:
import socket
try:
    socket.gethostbyaddr(your_ip_adrress)
except socket.herror:
    print u"Unknown host"
回答by PSS
As far as I understood the OP is looking for active connection FROMcertain ip, meaning he wants to check locally if there is active connection exists. It looks like something along lines of netstat to me. There are several options:
据我了解,OP 正在寻找来自某个 ip 的活动连接,这意味着他想在本地检查是否存在活动连接。对我来说,它看起来像是 netstat 的一些东西。有几种选择:
- You can use psutilsas demonstrated in thispost. You will want to cycle the active processes and query active connections. 
- You could use netstat.py- a clone of netstat by Jay Loden, Giampaolo Rodola' to do the job for you. 
- 您可以使用netstat.py- Jay Loden、Giampaolo Rodola 的 netstat 克隆来为您完成这项工作。 
Added:
补充:
You can do something like that:
你可以这样做:
import psutil
def remote_ips():
    '''
    Returns the list of IPs for current active connections
    '''
    remote_ips = []
    for process in psutil.process_iter():
        try:
            connections = process.get_connections(kind='inet')
        except psutil.AccessDenied or psutil.NoSuchProcess:
            pass
        else:
            for connection in connections:
                if connection.remote_address and connection.remote_address[0] not in remote_ips:
                    remote_ips.append(connection.remote_address[0])
    return remote_ips
def remote_ip_present(ip):
    return ip in remote_ips()
This is how it works:
这是它的工作原理:
>>>remote_ips()
['192.168.1.50', '192.168.1.15', '192.168.1.52', '198.252.206.16', '198.252.206.17'] 
>>>remote_ip_present('192.168.1.52')
True
>>>remote_ip_present('10.1.1.1')
False

