Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect fprintf output to a port

I have worked in Java and I know basic C.

I have to debug code which was not written by me. In my Java projects, I have been using log4j with the following configuration:

log4j.rootCategory=INFO, A1, socket
log4j.appender.socket=org.apache.log4j.net.SocketAppender
log4j.appender.socket.remoteHost=localhost
log4j.appender.socket.port=4445
log4j.appender.socket.locationInfo=true
log4j.appender.A1=org.apache.log4j.ConsoleAppender

After that I use the beanmill plugin in NetBeans to read the log so as to know the origin of the log. It is possible to search the source code for the string in the log output but that takes time and I have to do it for a lot of statements. Beanmill makes it as easy as clicking on a logged line.

Now I have to work with some C code which uses a lot of fprintf statements.

Any idea how I can achieve what I was doing with log4j and beanmill by redirecting fprintf output to port 4445?

I am working in Windows XP, with MinGW and NetBeans 7.3.

like image 560
Shiva Avatar asked Nov 03 '22 01:11

Shiva


1 Answers

In the snippet you have mentioned, you are basically writing to a socket which is localhost:4445.

You don't need to redirect fprintf to a port. You need to achieve socket communication using fprintf.

But a socket is not a file handle and so you cannot use fprintf in this case. You can use fprintfsock which is specially designed for working with sockets. On Windows, you can do something like this:

#define fprintf(a,b,...) fprintfsock(a,b,__VA_ARGS__)

void fprintfsock( SOCKET s, const char* f, ... )
{
    va_list a;
    va_start( a, f );
    //vsnprintf will return total number of characters excluiding null-terminator
    int l = vsnprintf( 0, 0, f, a ) + 1 ;
    char* buf = (char*) malloc(l);
    va_start( a, f );
    // vsnprintf will write at most l characters including null-terminator
    vsnprintf( buf, l, f, a );
    send( s, buf, l, 0 );
    free( buf );
}
like image 144
Saswat Padhi Avatar answered Nov 09 '22 16:11

Saswat Padhi