Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: How to receive a whole UDP Datagram

Tags:

go

udp

My Problem: With net.Read... Methods copy only the number of bytes of the size of the given byte-array or slice. I don't want to allocate the maximum UDP datagram of 64 kB every time of course.

Is there a go way to determine the size of the datagram (which is in the datagram header) or read again until the datagram is completely read?

like image 797
0x434D53 Avatar asked Feb 24 '14 10:02

0x434D53


People also ask

How do I get UDP packets?

To receive packets from all the sending hosts, specify the remote IP address as 0.0. 0.0 . Match the port number specified in the Local IP Port parameter with the remote port number of the sending host.

Does RECV work with UDP?

Unlike send(), the recv() function of Python's socket module can be used to receive data from both TCP and UDP sockets.

How big can a UDP payload be?

A UDP datagram is carried in a single IP packet and is hence limited to a maximum payload of 65,507 bytes for IPv4 and 65,527 bytes for IPv6. The transmission of large IP packets usually requires IP fragmentation.

Can UDP send and receive on same port?

TCP vs UDP Once connected, a TCP socket can only send and receive to/from the remote machine. This means that you'll need one TCP socket for each client in your application. UDP is not connection-based, you can send and receive to/from anyone at any time with the same socket.


1 Answers

Try ReadFromUDP:

func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)

ReadFromUDP reads a UDP packet from c, copying the payload into b. It returns the number of bytes copied into b and the return address that was on the packet.

The packet size should be available from n, which you can then use to define a custom slice (or other data structure) to store the datagrams in. This relies on the datagram size not changing during the session, which it really shouldn't.

like image 187
Intermernet Avatar answered Oct 11 '22 09:10

Intermernet