eckes
eckes

Reputation: 67067

How do I tell a socket to throw away all pending data without closing it?

Say I've got that application that uses sockets.

The server application reads some data, processes it and suddenly the server recognizes that something's wrong with the read data.

Now, the reading shall be aborted and everything sent by the client shall be thrown away.

Is there a socket function that I could call to achieve this? Or do I have to read() until there's nothing left in the socket?

I do not want to close the socket. Just drop the pending data.

Upvotes: 0

Views: 605

Answers (1)

cnicutar
cnicutar

Reputation: 182649

If you want to throw away all the data and instantly abort the connection, then you can set the SO_LINGER option and close.

setsockopt(fd, SOL_SOCKET, SO_LINGER,
    &(struct linger){.l_onoff=1, l_linger=0}, sizeof(struct linger));

This will immediately reset the connection (it will send a RST segment).

If however you want to throw some data, and keep the connection, this is likely not doable. There's no API (that I know of) to tell the kernel: "ignore the next 100 bytes: I don't want read to unblock on them". So you'll just have to call read until you decide the data is usable again.

Upvotes: 2

Related Questions