[英]Python raw udp packet not arriving at udp listener
I'm trying to send a custom UDP packet from a raw socket (On windows if that's relevant) to a udp listener on my VPS, but the packet never shows up at it's destination. 我正在尝试从原始套接字(在Windows上,如果相关的话)向我的VPS上的udp监听器发送自定义UDP数据包,但数据包永远不会出现在它的目的地。
Client: import struct import socket 客户端:import struct import socket
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))
Server: 服务器:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", 10101))
while True:
msg, addr = s.recvfrom(1024)
print msg, addr
I can send a uniform udp packet and it will arrive successfully like so: 我可以发送一个统一的udp数据包,它会成功到达:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("asdf", ("vps ip", 10101))
Help? 救命?
In make_udp_header
change the datal from +16
to +8
. 在make_udp_header
将数据从+16
更改为+8
。 That seemed to work for me. 这似乎对我有用。
change these few lines 改变这几行
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))
By 通过
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)
Hopefully this is what you were looking for !! 希望这是你想要的!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.