首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python原始udp数据包未到达udp侦听器

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

Stack Overflow用户
提问于 2014-07-02 07:41:44
回答 2查看 3.1K关注 0票数 3

我试图从一个原始套接字(如果相关的话在windows上)发送一个自定义的UDP包到我的VPS上的udp监听器,但是这个包从来没有出现在它的目的地。

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

代码语言:javascript
复制
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))

服务器:

代码语言:javascript
复制
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数据包,它将成功到达,如下所示:

代码语言:javascript
复制
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("asdf", ("vps ip", 10101))

帮助?

EN

回答 2

Stack Overflow用户

发布于 2015-02-19 01:38:13

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

票数 1
EN

Stack Overflow用户

发布于 2014-11-29 08:23:13

更改这几行

代码语言:javascript
复制
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))

通过

代码语言:javascript
复制
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
packet = makepacket(("my ip", 1000), ("vps ip", 10101), "asdf")
s.connect(('vps ip',10101))
s.send(packet)

希望这就是你要找的!!

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24520799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档