Getting all IP addresses connected to WiFi using python and scapy

Viewed 343

How would I get the IP addresses of all ips connected to wifi (that I am on). I tried doing it by using sniff() and getting all src IP of those packets using the following lines:

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))

But this rarely gets me all IP's, so how would I pull that off using python and (if needed) scapy?

1 Answers

Forgive me if I'm misunderstanding your question.. what you're trying to do is map all live hosts on your LAN?

A simpler approach is to use the builtin ipaddress and socket libraries. For each IP in your LAN subnet, try connecting a socket to various ports (TCP/UDP). If a connection is established, a host exists at that IP.

Here's some code I can think of that might solve your problem (I have not tested this myself)

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)}")

Related