AnkurVj
AnkurVj

Reputation: 8218

Can descriptors for sockets be converted to File Pointers?

I got a descriptor for a TCP socket in the following manner :

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

Now from this descriptor desc I want to get a file pointer. Can fdopen() be used here ?

The reason I want to get a file pointer is because I am making changes to an existing code that writes data to a local file. Now, I want to extend its functionality so that it can alternatively write to a TCP client. I dont want to rewrite all functions and was thinking of somehow being able to use the existing infrastructure. The existing functions use the file pointer to write to the file. I was wondering if it was possible to make the same function write to a TCP stream without making any changes.

Upvotes: 8

Views: 4585

Answers (1)

user405725
user405725

Reputation:

Yes, fdopen() is exactly what you need. Here is what man page is saying about it:

The fdopen() function associates a stream with the existing file descriptor, fd. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fd, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, 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 may send data differently (i.e. flush whenever \n is found in the stream, insert \r) etc.

Upvotes: 10

Related Questions