Search code examples
pythonscapy

Is there a way to get Hostnames with Scapy in Python?


I made a simple IP Scanner which I use to scan the Local Network. I want to get the Hostname like Nmap. Is there a way to get every Hostname in the local network with scapy.all? Here is my Python Script where I want insert the Hostname:

import scapy.all as scapy


request = scapy.ARP()
broadcast = scapy.Ether()
broadcast.dst = 'ff:ff:ff:ff:ff:ff'
available_networks = []


def IP_Scan(net_area, net_mask):
    available_networks.clear()
    request.pdst = f'{net_area}/{net_mask}'
    request_broadcast = broadcast / request
    clients = scapy.srp(request_broadcast, timeout=5)[0]
    for sent_ip, received_ip in clients:

        available_networks.append({'IP': received_ip.psrc, 'MAC': received_ip.hwsrc})

    return available_networks```
  

Solution

  • Scapy doesn't provide that because it already exists via Python's socket module:

    import scapy.all as scapy
    import socket
    
    request = scapy.ARP()
    broadcast = scapy.Ether()
    broadcast.dst = 'ff:ff:ff:ff:ff:ff'
    available_networks = []
    
    
    def IP_Scan(net_area, net_mask):
        available_networks.clear()
        request.pdst = f'{net_area}/{net_mask}'
        request_broadcast = broadcast / request
        clients = scapy.srp(request_broadcast, timeout=5)[0]
        for sent_ip, received_ip in clients:
    
            available_networks.append({'IP': received_ip.psrc, 
                                       'MAC': received_ip.hwsrc, 
                                       'HOSTNAME': socket.gethostbyaddr(received_ip.psrc)[0]})
    
        return available_networks
    

    In the code 'HOSTNAME': socket.gethostbyaddr(received_ip.psrc)[0], you need index zero to get the hostname. Add checks in case that's missing in the returns.