简体   繁体   English

使用python raw socket读取完整的数据包

[英]Reading full packet using python raw socket

I am trying to create a raw socket for UDP packets only to do IP forwarding, using forwarding table. 我正在尝试使用转发表为UDP数据包创建原始套接字,以仅进行IP转发。 I am not expert in raw socket programming and my concern is how to assure that a complete UDP packet in the buffer. 我不是原始套接字编程专家,我关心的是如何确保缓冲区中有完整的UDP数据包。

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s.bind(('0.0.0.0', 1337))
while True:
    packet = s.recvfrom(65535) #how to know that I read the complete packet not 50% or 1 and half packet 
    forwared_packet_function(packet) #here I will parse the packet change ip header and update the IP table and forward the packet

Is it possible to tell me how can I read one full packet by recvfrom() ? 是否可以告诉我如何通过recvfrom()读取一个完整的数据包?

I am not expert in raw socket programming too, but I have some knowledge of network. 我也不是原始套接字编程的专家,但是我对网络有一定的了解。

1st Question: 第一个问题:

how to know that I read the complete packet not 50% or 1 and half packet? 怎么知道我读的不是完整的数据包而不是50%或1个半数据包?

Answer: You can't. 答:不能。 It don't have "sequence number" or "acknowledgement number" like TCP. 它没有像TCP这样的“序列号”或“确认号”。

2nd Question: 第二个问题:

Is it possible to tell me how can I read one full packet by recvfrom()? 是否可以告诉我如何通过recvfrom()读取一个完整的数据包?

Answer: Let try 答:让我们尝试

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s.bind(('0.0.0.0', 1337))
while True:
    packet = s.recvfrom(65535).decode()    #decode packet
    forwared_packet_function(packet)
    print(packet)   #print packet to read

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

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