How To Generate TCP, IP And UDP Packets In Python

Prakash Pandey picture Prakash Pandey · Nov 19, 2011 · Viewed 34.7k times · Source

Can anyone tell me the most basic approach to generate UDP, TCP, and IP Packets with Python?

Answer

Muayyad Alsadi picture Muayyad Alsadi · Nov 20, 2011

As suggested by jokeysmurf, you can craft packets with scapy

If you you want to send/receive regular, i.e. non-custom, packets then you should use socket or socketserver:

For example, to send a TCP HTTP GET request to Google's port 80 use:

    import socket
    HOST = 'google.com'    # The remote host
    PORT = 80              # The same port as used by the server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    s.send('GET / HTTP/1.1\r\nHost: google.com\r\n\r\n')
    data = s.recv(1024)
    s.close()
    print 'Received', repr(data)

To send UDP instead of TCP change SOCK_STREAM to SOCK_DGRAM.