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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With