Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading partially from sockets

Tags:

sockets

udp

I'm having a little test program that sends a lot of udp packets between client->server->client (ping/pong test). The packets are fixed size on each run(last run is max allowable size of udp packet) I'm filling the packets with random data except for the beginning of each packet that contains the packet number. So I'm only interested to see if I receive all the packets back at the client.

I'm using sendto() and recvfrom() and I only read the sizeof(packet_number) (which in this case is an int). What happens to the rest of the data? Does it end up in fairyland (gets discarded)? or does the new packet that arrives gets appended to this "old" data?

(using linux)

like image 220
NomadAlien Avatar asked Jun 18 '10 11:06

NomadAlien


People also ask

Can a socket be simultaneously read and written?

One thread reading and one thread writing will work as you expect. Sockets are full duplex, so you can read while you write and vice-versa. You'd have to worry if you had multiple writers, but this is not the case.

Is read from socket blocking?

By default, TCP sockets are in "blocking" mode. For example, when you call recv() to read from a stream, control isn't returned to your program until at least one byte of data is read from the remote site. This process of waiting for data to appear is referred to as "blocking".

How do I know if my socket is connected?

If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

How do you know if a socket has been closed?

The only way to tell if the socket has been disconnected is to send data over it. set the timeout on the server side socket and then have the client check in every so often within the timeout so if you set the client to check in every 10 seconds then set the timeout to say 30 seconds on the server socket.


1 Answers

Each read from UDP socket de-queues one whole datagram off kernel socket receive buffer no matter what's your userland buffer size. That is:

  • If your buffer is bigger then the next pending datagram, you'll read less then your buffer size.
  • If your buffer is smaller, you'll read your buffer size worth and the rest of the data is discarded.
  • You can set MSG_TRUNC option in the flags, so recv(2) will return the whole datagram length, not just the part you read into your userland buffer.

Hope this helps.

like image 111
Nikolai Fetissov Avatar answered Nov 01 '22 08:11

Nikolai Fetissov