Skip to content

Instantly share code, notes, and snippets.

@Nazarii
Last active July 26, 2016 08:00
Show Gist options
  • Select an option

  • Save Nazarii/8a3747df0d0ab8a70a82 to your computer and use it in GitHub Desktop.

Select an option

Save Nazarii/8a3747df0d0ab8a70a82 to your computer and use it in GitHub Desktop.
Network unitest
#!/usr/bin/env python
import unittest
import time
import netinfo
import threading
from scapy.all import send, sniff, conf, IP, TCP
UNIQUE_MESSAGE = 'Errors should never pass silently'
class TestSniffPackets(unittest.TestCase):
"""Test case to test network packets transporting.
Pre-requirements:
$ sudo apt-get install python-dev
$ sudo pip install scapy
$ sudo pip install pynetinfo"""
def setUp(self):
"""Setting default network interface to sniff."""
conf.iface = [iface['dev'] for iface in netinfo.get_routes()
if iface['dest'] == '0.0.0.0'][0]
def sniff(self, packets_filter, min_len):
packets = sniff(filter=packets_filter, timeout=30)
self.assertGreater(len(packets), min_len)
def test_sniff_tcp(self):
"""Answer: let's say you have a web server running on your pc on port
8069 and it is reachable in the network. Another user from your network
can run command 'curl <youripaddress>:8069 - it will send TCP packet's
to your webserver.
Or he can use Netcat:
echo -n “foo” | nc -4u -w1 <youripaddress> <udp port>"""
self.sniff('tcp', 100)
def test_sniff_icmp(self):
"""Answer: another user from your network can send you ICMP packets by
pinging your IP address (or by using traceroute):
ping <youripaddress>"""
self.sniff('tcp', 10)
def test_sniff_udp(self):
"""Answer: another user from your network can send you UDP packets by
using Netcat:
nc -u <youripaddress> 53 << /dev/random"""
self.sniff('udp', 50)
def send_packet_thread(self):
time.sleep(0.5)
packet = IP(dst="0.0.0.0")/TCP()/UNIQUE_MESSAGE
send(packet)
def rcv_packet_thread(self):
while True:
packet = sniff(filter='tcp', count=1)[0]
if hasattr(packet, 'load') and packet.load == UNIQUE_MESSAGE:
break
def test_send_recv_packet(self):
"""Check whether sent packet is received"""
send_thread = threading.Thread(target=self.send_packet_thread)
rcv_thread = threading.Thread(target=self.rcv_packet_thread)
send_thread.start()
rcv_thread.start()
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment