Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline over a socket

Tags:

c

sockets

stdio

Is there a libc function that would do the same thing as getline, but would work with a connected socket instead of a FILE * stream ?

A workaround would be to call fdopen on a socket. What are things that should be taken care of, when doing so. What are reasons to do it/ not do it.

One obvious reason to do it is to call getline and co, but maybe it is a better idea to rewrite some custom getline ?

like image 253
shodanex Avatar asked Jan 24 '23 02:01

shodanex


1 Answers

when you call a read on a socket, then it can return a zero value prematurely. eg.

 read(fd, buf, bufsize)

can return a value less than bufsize if the kernel buffer for the tcp socket is full. in such a case it may be required to call the read function again unless it returns a zero or a negative result.

thus it is best to avoid stdio functions. you need to create wrappers for the read function in order to implement the iterative call to read for getting bufsize bytes reliably. it should return a zero value only when no more bytes can be read from the socket, as if the file is being read from the local disk.

you can find wrappers in the book Computer Systems: A Programmer's Perspective by Randal Bryant.

The source code is available at this site. look for functions beginning with rio_.

like image 102
Rohit Banga Avatar answered Feb 03 '23 13:02

Rohit Banga