Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from socket

Tags:

c

sockets

I need to read from an AF_UNIX socket to a buffer using the function read from C, but I don't know the buffer size.

I think the best way is to read N bytes until the read returns 0 (no more writers in the socket). Is this correct? Is there a way to guess the size of the buffer being written on the socket?

I was thinking that a socket is a special file. Opening the file in binary mode and getting the size would help me in knowing the correct size to give to the buffer?

I'm a very new to C, so please keep that in mind.

like image 785
Donovan Avatar asked Jun 16 '10 13:06

Donovan


People also ask

What is a socket read?

Behavior for sockets: The read() call reads data on a socket with descriptor fs and stores it in a buffer. The read() all applies only to connected sockets. This call returns up to N bytes of data. If there are fewer bytes available than requested, the call returns the number currently available.

How do you read socket data?

Reading Data From a SocketServerSocket server = new ServerSocket(port); Socket socket = server. accept(); DataInputStream in = new DataInputStream(new BufferedInputStream(socket. getInputStream())); Note that we've chosen to wrap the socket's InputStream in a DataInputStream.

What does read () in C do?

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file.


1 Answers

On common way is to use ioctl(..) to query FIONREAD of the socket which will return how much data is available.

int len = 0;
ioctl(sock, FIONREAD, &len);
if (len > 0) {
  len = read(sock, buffer, len);
}
like image 83
epatel Avatar answered Oct 03 '22 22:10

epatel