且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 中生成 TCP、IP 和 UDP 数据包

更新时间:2023-11-09 20:28:10

根据jokeysmurf 的建议,您可以使用scapy

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:

例如,要向 Google 的端口 80 发送 TCP HTTP GET 请求,请使用:

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)

要发送 UDP 而不是 TCP,请将 SOCK_STREAM 更改为 SOCK_DGRAM.

To send UDP instead of TCP change SOCK_STREAM to SOCK_DGRAM.