views:

96

answers:

4

I have an existing C program which prints a number of messages to standard error using:

fprintf(stderr, ...

I would like to modify this program so that these messages are also sent out over a TCP connection across the Internet. (Which I have already created as a SOCK_STREAM socket.) What's the best way format the messages like they would be by fprintf and then send them out across the Internet?

Of course, before I can send a message I first need to know how long it is, so I can send the length out to the client first, so the client will know how many bytes to read in...

Any ideas would be most appreciated!

A: 

I think you need to look at sprintf or (better) the variant that requires you to supply an explicit out buffer size.

Stephen C
+2  A: 

Once you have your socket connected, you can open it as a stream using fdopen() on the socket file descriptor. That'll give you a FILE * that you can pass to fprintf() in place of stderr.

caf
Thanks, but I thought of that, and as far as I can tell, in order for the client to know how many byes to read in for each message, I will first need to send the length of the message ahead of time. I don't think that can be done by just passing FILE * in place of stderr...
Charles
Well, if all your messages finish with a `\n` then the client can just read until it sees one.
caf
...which is easy to do using `fgets()`, `fscanf()`, etc. on the reading side once you have a `FILE *` using `fdopen()`.
mark4o
+1  A: 

I would suggest you wrap the output calls in a variable argument function (its how the printf family of functions work) and do everything from there. For example it might look like:

int multi_log(FILE * stream, int fd, const char * fmt, ...) {
   char buff[BUFF_MAX] = {0};
   int len = 0;
   va_list args;
   va_start (args, fmt);
   len = vsnprintf (buff, BUFF_MAX, fmt, args);
   va_end (args);

   fputs (buff, stream);
   write (fd, buff, len); 
}

That way you can add and/or remove functionality as needed.

Caveats apply for using the size returned from vsnprintf, read you man pages carefully

ezpz
A: 

Take a look at the following articles:

http://ferozedaud.blogspot.com/2009/11/how-to-send-object-from-java-to-net.html

http://ferozedaud.blogspot.com/2009/11/howto-serialize-data-from-object-from.html

While these articles are using .NET and Java, you can use the same principles for Native socket code as well. Basically, you need to use Message Framing to delimit your data.

feroze