I am trying to create a port scanner (using SYN packets) with the sockets library (yes I know scapy would make this much easier, but I'm mostly doing this for a learning exercise.) I have crafted the packet and successfully sent it, however I'm having troubled receiving and parsing the subsequent response.
So far I've tried the s.recv(1024)
and 4096, as well as recvfrom()
.
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
s.sendto(packet, (dstip, 80))
r = s.recv(1024)
print(r)
However, I am having trouble receiving the response, I can see that the packet is being sent correctly via Wireshark, and the SYN-ACK is sent to my machine, however I am unable to properly receive and print it. Is there a better way I can use the s.recv()
function for this sort of input? Or am I using the wrong function?
Any help is appreciated, I'm new to the sockets library. Thanks.
The book Black Hat Python has en example using the socket library to create a scanner, unfortunately not a port scanner. They check if a host is up, and they use a raw socket to receive data. The code is available here.
They are sending SYN-packets with one socket object in a new thread, and sniffing the replies using another socket object.
In the example they use socket.IPPROTO_IP
or socket.IPPROTO_ICMP
instead of socket.IPPROTO_RAW
depending on if it is Windows or not.
For the sniffer they use the function setsockopt(socket.IPPROTO_IP,
socket.IP_HDRINCL, 1)
for sniffing, where IPPROTO_IP
is a dummy-protocol for TCP, IP_HDRINCL
is to include headers in the IP packets, and 1 is mapped to the ICMP-protocol in the code.
Good luck!