Debugging output through network
Send debugging output through UDP protocol
Introduction
When you need to receive debugging messages from a program running on another machine, one option is to send the messages across the network so they can be viewed elsewhere. In order to implement this, I wrote a class library that uses the UDP protocol so that interruption of program can be avoided while sending message packets. The library is very simple, so I am only providing the class source files, which can be downloaded from the above link.
Procedure to use class library
- Include the source files in your project.
- Add following code to your source code.
#include "NetDebug.h" // To make things as simple as possible, // all functions in the CNetDebug class are declared as static // so you don't need to create an instance. // CNetDebug::Init() is optional. // If your program doesn't call WSAStartup(), call the Init() function. CNetDebug::Init(); // Set destination IP and port number. CNetDebug::SetAddr("192.168.10.173", 12345); // Once set up as shown you can print messages wherever you want. // just as with printf int num1 = 100, num2=200; CNetDebug::Write("Checking number=%d number2=%d", num1, num2); // Cleanup Winsock before exiting program CNetDebug::Deinit();
- Add Ws2_32.lib to the link modules in the project setting.
Using Macros
In addition, the class includes macros to enable and disable the debugging feature at compile time. To enable this, simply use the macros instead of directly using the class.
NET_DEBUG_INIT(); NET_DEBUG_SET_ADDR("192.168.10.173", 12345); ... char msg[] = "Hello World!!"; NET_DEBUG(("Greeting [%s]", msg)); // Be careful, requires double parentheses. ... NET_DEBUG_DEINIT();You can simply drop the debugging code by defining "_NO_NET_DEBUG" constant.
Receiving the Messages
Now that your program will send messages across the network, you need a way to collect the messages. Don't worry! This is easily done by creating a very simple server program. I use the following PHP code to get the messages, since I think PHP is much easer to use than C++ for this purpose.
///// PHP Code Begin
<?
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if (!$s) die('create error');
$bind_ip = "192.168.10.173"; // host ip address
$bind_port = 12345;
if (!socket_bind($s, $bind_ip, $bind_port)) die('bind error');
while ( true ) {
socket_recvfrom($s, $buf, 1024, 0, $ip, $port);
echo date("H:i:s"), " $ip -> ", $buf, "\n";
}
socket_close($s);
?>