使用 python 和 scapy 获取所有连接到 WiFi 的 IP 地址

Getting all IP addresses connected to WiFi using python and scapy

我如何获取所有连接到 wifi(我打开的)的 ip 的 IP 地址。我尝试通过使用 sniff() 并使用以下行获取这些数据包的所有 src IP 来做到这一点:

ips = []
    captured = sniff(count=200)
        for i in range(len(captured)):
            try:
               rpp = captured[i].getlayer(IP).src
                if "192." in rpp and rpp != router_ip:
                    ips.append(rpp)
            ips = list(set(ips))

但这很少让我获得所有 IP,所以我如何使用 python 和(如果需要)scapy 来实现它?

如果我误解了你的问题,请原谅我。你想做的是映射你 LAN 上的所有实时主机?

一种更简单的方法是使用内置 ipaddresssocket 库。对于 LAN 子网中的每个 IP,尝试将套接字连接到各种端口 (TCP/UDP)。如果建立了连接,则该 IP 上存在主机。

这是我能想到的一些代码,可能会解决您的问题(我自己还没有测试过)

import socket
import ipaddress

live_hosts = []

# google popular tcp/udp ports and add more port numbers to your liking
common_tcp_ports = [23, 80, 443, 445]
common_udp_ports = [67, 68, 69]

def scan_subnet_for_hosts(subn = '192.168.1.0/24'):
    network = ipaddress.IPv4Network(subn)
    for ipaddr in list(network.hosts()):
        for port in common_tcp_ports:
             try:
                 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
                 s.connect((str(ipaddr), port))
                 live_hosts.append(ipaddr)
             except socket.error:
                 continue
        for port in common_udp_ports:
             try:
                 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
                 # UDP is connectionless, so you might have to try using s.send() as well
                 s.connect((str(ipaddr), port))
                 live_hosts.append(ipaddr)
             except socket.error:
                 continue

scan_subnet_for_hosts()
for host in live_hosts:
    print(f"Found live host: {str(host)}")