Tuesday, April 8, 2008

Send a binary message using netcat on windows

Consider that you need to send an echo message to a service that expects the echo in a binary format. If a correctly formatted binary message is sent to the service it will respond with a correctly formatted response over the same connection.

I was tasked with this at work today and here is what I came up with.

I used JScript running under the Windows Scripting Host ( WSH ) to:
create a WshShell objectexecute a WshShell.Exec to run a shell command on the host machine to use netcat to send the binary file and pipe the output into a receivedData.bin file.
execute a WshShell.Exec to use the windows command line tool, "FC" to compare the received file with a known existing file.


//JScript - executed under the Windows Scripting Host ( cscript )
//var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec( "%comspec% /c c:\\myScripts\nc.exe 192.168.0.2 1234 <> c:\\myScripts\\recData.bin" );
//Keep checking for a valid status code and if found break out or break out after 10 seconds
tryCount = 0;

do while ( true ) {
if( tryCount ++ > 10 || oExec.Status == 1 ) {
break;
} else {
WScript.Sleep(100);
}
}

//Do the file compare
oExec = WshShell.Exec( "%comspec% /c fc /B c:\\myScripts\\correctEchoResponse.bin c:\\myScripts\\recData.bin" );

//Again - Wait 10 seconds or break if command complete
tryCount = 0;
do while ( true ) {
if( tryCount ++ > 10 || oExec.Status == 1 ) {
break;
} else {
WScript.Sleep(100);
}
}

//Check the exit code and report results.
if( oExec.ExitCode != 1 ) {
WScript.Echo( "FAILED MATCH" );
} else {
WScript.Echo( "SUCCESSFUL MATCH" );
}


So that's it really. The script should work. ( This is written mostly from memory so it might need a bit of debugging but the concepts are there.)

More info: http://msdn2.microsoft.com/en-us/library/ateytk4a(VS.85).aspx