Python 原始 udp 数据包未到达 udp 监听器

标签 python sockets networking udp

我正在尝试将自定义 UDP 数据包从原始套接字(如果相关,则在 Windows 上)发送到我的 VPS 上的 udp 监听器,但该数据包从未出现在它的目的地。

客户: 导入结构 导入套接字

def make_ipv4_header(srcip, dstip, datal, srcprt, dstprt):
    srcip = socket.inet_aton(srcip)
    dstip = socket.inet_aton(dstip)

    ver = 4     #Version 4 for IPv4
    ihl = 5     #Header length in 32 bit words. 5 words == 20 bytes
    dscp_ecn = 0#Optional fields, don't feel like implementing. Let's keep it at 0
    tlen = datal + 28 #Length of data + 20 bytes for ipv4 header + 8 bytes for udp     header
    ident = socket.htons(54321) #ID of packet
    flg_frgoff = 0 #Flags and fragment offset
    ttl = 64 #Time to live
    ptcl = 17 #Protocol, 17 (UDP)
    chksm = 0 #Will automatically fill in checksum    

    return struct.pack(
        "!"     #Network(Big endian)
        "2B"    #Version and IHL, DSCP and ECN
        "3H"    #Total Length, Identification, Flags and Fragment Offset
        "2B"    #Time to live, Protocol
        "H"     #Checksum
        "4s"    #Source ip
        "4s"    #Destination ip
        , (ver << 4) + ihl, dscp_ecn, tlen, ident, flg_frgoff, ttl, ptcl, chksm, srcip, dstip)

def make_udp_header(srcprt, dstprt, datal):
    return struct.pack(
        "!4H"   #Source port, Destination port, Length, Checksum
        , srcprt, dstprt, datal+16, 0)

def makepacket(src, dst, data):
    ph = make_ipv4_header(src[0], dst[0], len(data), src[1], dst[1])
    uh = make_udp_header(src[1], dst[1], len(data))
    return ph+uh+data

s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
packet = makepacket(("my ip", 1000), ("vps ip", 10101), "asdf")
s.sendto(packet, ("vps ip", 10101))

服务器:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 10101))
while True:
    msg, addr = s.recvfrom(1024)
    print msg, addr

我可以发送一个统一的 udp 数据包,它会像这样成功到达:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("asdf", ("vps ip", 10101))

帮忙吗?

最佳答案

make_udp_header 中,将数据从 +16 更改为 +8。这似乎对我有用。

关于Python 原始 udp 数据包未到达 udp 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24520799/

相关文章:

java - 如何在端口扫描器 java 实现中检测服务器状态

java - Android : Socket - java.net.SocketException: sendto 失败: EPIPE (Broken pipe)

docker - docker 参数 --net=container :ReportWeb in the docker run command 的 docker-compose 等价物是什么

macos - 运行错误 'Remote Debugger' : Unable to open debugger port (localhost:5005): java.net.ConnectException "Connection refused (Connection refused)"

python - 使用 CentOS 6.4 修复 Python 2.7 上的 "warning: GMP or MPIR library not found; Not building Crypto.PublickKey._fastmath"错误

python - 在 python 中分组,列具有 N/A 值

python - 管理站点中的 Django DateTimeField 编辑

sockets - 在套接字编程中,accept() 可以在多进程(线程)中使用同一个监听套接字吗?

java - 此流相关代码的 C# 等效项 (Java)

python - 使用 Python 进行组合词匹配的正则表达式