简体   繁体   中英

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. I am not expert in raw socket programming and my concern is how to assure that a complete UDP packet in the buffer.

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() ?

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?

Answer: You can't. It don't have "sequence number" or "acknowledgement number" like TCP.

2nd Question:

Is it possible to tell me how can I read one full packet by 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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