简体   繁体   English

用 Python 构建 UDP 数据包

[英]Building UDP packet in Python

There's already a code in the internet which shows how to build and send a TCP packet in Python using raw sockets, but I desperately need an example of how building a UDP one.互联网上已经有一段代码展示了如何使用原始套接字在 Python 中构建和发送 TCP 数据包,但我非常需要一个如何构建 UDP 数据包的示例。

I read this link http://www.ietf.org/rfc/rfc768.txt and understands that udp header consists only of src ip, src port, length and checksum, and also read that if I create an IPPROTO_UDP socket instead of IPPROTO_RAW socket, the IP header should be filled automatically by the kernel.我阅读了此链接http://www.ietf.org/rfc/rfc768.txt并了解 udp 标头仅包含 src ip、src 端口、长度和校验和,并且如果我创建 IPPROTO_UDP 套接字而不是 IPPROTO_RAW,则还阅读套接字,IP 标头应由内核自动填充。

Yet, I had no success in doing such.然而,我没有成功这样做。

Here's the code building tcp packets with raw socket:这是使用原始套接字构建 tcp 数据包的代码:

import socket
import struct

def make_ip(proto, srcip, dstip, ident=54321):
    saddr = socket.inet_aton(srcip)
    daddr = socket.inet_aton(dstip)
    ihl_ver = (4 << 4) | 5
    return struct.pack('!BBHHHBBH4s4s' , 
                       ihl_ver, 0, 0, ident, 0, 255, proto, 0, saddr, daddr)

def make_tcp(srcport, dstport, payload, seq=123, ackseq=0,
             fin=False, syn=True, rst=False, psh=False, ack=False, urg=False,
             window=5840):
    offset_res = (5 << 4) | 0
    flags = (fin | (syn << 1) | (rst << 2) | 
             (psh <<3) | (ack << 4) | (urg << 5))
    return struct.pack('!HHLLBBHHH', 
                       srcport, dstport, seq, ackseq, offset_res, 
                       flags, window, 0, 0)

srcip = dstip = '127.0.0.1'
srcport, dstport = 11001, 11000
payload = '[TESTING]\n'

ip = make_ip(socket.IPPROTO_TCP, srcip, dstip)
tcp = make_tcp(srcport, dstport, payload)
packet = ip + tcp + payload

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
s.sendto(packet, (dstip, 0))
response, addr = s.recvfrom(65535)
response_id = struct.unpack('!H', response[4:6])
print response_id

How to make the same thing with UDP instead?如何用UDP做同样的事情?

Best solution for me is just editing the existing code, since reading abstract information didn't help me much.对我来说最好的解决方案就是编辑现有的代码,因为阅读抽象信息对我没有多大帮助。

I'm using Python 2.7 on Windows XP.我在 Windows XP 上使用 Python 2.7。

Just this:只是这个:

import socket
sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP
sock.bind((IP,PORT))

To send:发送:

sock.sendto(message,(IP,PORT))

To receive:接收:

sock.recvfrom(1024)

The 1024 displays the buffer size. 1024 显示缓冲区大小。 There are not other changes necessary as far as the socket part就插座部分而言,没有其他必要的变化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM