Skip to content

Commit 0bcb80c

Browse files
committed
feat: sniffer basic code implementation
1 parent 6e6b3c7 commit 0bcb80c

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Black Hat Python/chapter_03/README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
### sniffer_basic.py
2+
3+
```
4+
sudo python3 sniffer_basic.py
5+
```
6+
If running in local machine input the ip address which can be got by running `ipconfig` on Windows and `ipconfig getifaddr en0` on macOS
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import socket
2+
import os
3+
4+
def main():
5+
# host to listen on
6+
HOST = input("Enter the IP address to listen on: ")
7+
8+
# create raw socket, bind to public interface
9+
if os.name == 'nt':
10+
socket_protocol = socket.IPPROTO_IP
11+
else:
12+
socket_protocol = socket.IPPROTO_ICMP
13+
14+
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket_protocol)
15+
sniffer.bind((HOST, 0))
16+
17+
# include the IP header in the capture
18+
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
19+
20+
if os.name == 'nt':
21+
sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
22+
23+
# read one packet
24+
print(sniffer.recvfrom(65565))
25+
26+
# if we're on Windows, turn off promiscuous mode
27+
if os.name == 'nt':
28+
sniffer.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
29+
30+
if __name__ == '__main__':
31+
main()

0 commit comments

Comments
 (0)