Skip to content

Instantly share code, notes, and snippets.

@mpoerwito
Last active November 17, 2022 18:40
Show Gist options
  • Save mpoerwito/477e29d7d175226d88f690e405bdcc6d to your computer and use it in GitHub Desktop.
Save mpoerwito/477e29d7d175226d88f690e405bdcc6d to your computer and use it in GitHub Desktop.
using scapy to scan the network by sending/receiving ARP packets
import socket
from time import sleep
from scapy.layers.l2 import ARP, Ether
from scapy.all import *
def arpscan(network):
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
for i in range(1,20):
targetIP = network + str(i)
arp = ARP(pdst=targetIP)
arprcvd = srp1(ether/arp, timeout=2)
if arprcvd is not None:
print(f"IP: {arprcvd[0].psrc} | MAC: {arprcvd[0].hwsrc}")
sleep(0.5)
def netscanner(network):
# IP Address for the destination
target_ip = network
""" Create packets """
# create ARP packet
arp = ARP(pdst=target_ip)
# create the Ether broadcast packet
# ff:ff:ff:ff:ff:ff MAC address indicates broadcasting
ether = Ether(dst="ff:ff:ff:ff:ff:ff")
# stack them
packet = ether/arp
# send packets using srp() function which sends and receives packets at layer 2
# set the timeout to 3 so the script won't get stuck
result = srp(packet, timeout=3)[0]
# a list of clients, we will fill this in the upcoming loop
clients = []
for sent, received in result:
# for each response, append ip and mac address to `clients` list
clients.append({'ip': received.psrc, 'mac': received.hwsrc})
print("Devices found in the network:")
print("IP" + " "*18+"MAC")
for client in clients:
print(f"{client['ip']:16} {client['mac']}")
def main():
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
netid = ip[:ip.rfind(".")+1]
# print(f"host: {hostname} | ip a: {ip} -> netID: {netid}")
arpscan(netID)
if __name__ == "__main__":
main()
# netscanner("192.0.0.1/26")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment