Can anyone tell me the most basic approach to generate UDP, TCP, and IP Packets with Python?
            Asked
            
        
        
            Active
            
        
            Viewed 4.2k times
        
    2 Answers
10
            
            
        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:
- http://docs.python.org/library/socket.html#module-socket
- http://docs.python.org/library/socketserver.html#module-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.
 
    
    
        d-cubed
        
- 1,034
- 5
- 30
- 58
 
    
    
        Muayyad Alsadi
        
- 1,506
- 15
- 23
- 
                    The socket is based on transport layer, you see the s.connect lose sight of SYN ACK packets. – aircraft Aug 20 '20 at 08:53
6
            
            
        You can do interactive packet manipulation with scapy.
This article is going to get you started on gluing together an IP packet.
Construction of a tcp packet is as easy as:
packet = IP(src="10.0.0.10")
 
    
    
        Peter O.
        
- 32,158
- 14
- 82
- 96
 
    
    
        jokeysmurf
        
- 81
- 1
