Can socket descriptors be converted to file pointers?

I got the handle for the TCP socket as follows:

int desc = accept(socket_descriptor, &client_address, &len)

Now from this desc descriptor I want to get a file pointer. Is it possible to use fdopen() here?

The reason I want to get a pointer to a file is because I am making changes to existing code that writes data to a local file. Now I want to expand my functionality so that it can be written to the TCP client as an alternative. I donโ€™t want to rewrite all the functions and thought about somehow using the existing infrastructure. Existing functions use a file pointer to write to a file. I was wondering if it is possible to make the same function of writing to a TCP stream without any changes.

+7
source share
1 answer

Yes, fdopen() is exactly what you need. Here's what the man page says:

The fdopen () function associates a stream with an existing file descriptor, fd. The stream mode (one of the values โ€‹โ€‹"r", "r +", "w", "w +", "a", "a +") must be compatible with the file mode descriptor. The file position indicator for the new stream is set to which fd belongs, and the error indicators and the end of the file are cleared. The "w" or "w +" modes do not cause file truncation. the file descriptor is not duplicated and will be closed when the stream created by fdopen () is closed. The result of applying fdopen () to a shared memory object is undefined.

But use it with caution when applying to socket descriptors. High-level I / O functions use buffering and can send data in different ways (for example, with every \n in the stream, insert \r ), etc.

+8
source

All Articles