[dmh2000] - a telnet console in your Win32 application

daveh at dmh2000 dot com

[home]

Get Firefox!

Developed with jEdit

bricks

If you are used to programming in a Unix/Linux environment, then you know that you can SSH or telnet into a remote system, get a command shell, run interactive console programs, give keyboard input and observe their output. No big deal. But in Windows, its not so easy. There is no real support for remote command line access in the same sense. What is a developer to do?

One solution : put a telnet console right into your application. The basic telnet protocol makes it easy to include a simple telnet server as part of your application. This will let you telnet into the program remotely and interact with it. In this case you don't get a full command shell. You get the capability to read character input and write character output from your program. What you do with it is up to you.

All you need to do in the application is open a TCP stream socket, bind it to a user port, and wait for a connection. Once you get a connection from a telnet client on some remote machine (or even the local machine) you read and write characters. The telnet protocol supports various options and negotiations, but you can ignore those if you like and most clients will still work (I haven't found any that don't).

Application notes

Here is downloadable code for a library supporting the inclusion of a telnet server in your application, along with a simple example. It is written for Win32 sockets, although it would be easy to port to Linux or say, vxWorks sockets.

program structure example

	/*  ================================ */
	/*  outer loop waits for connections */
	/*  ================================ */
	for(;;) {
		/*  wait for a connection */
		status = telnet_connect(t,&addr,&port);
		if (status != 0) {
			/*  accept socket failed for some reason, quit completely */
			break;
		}
		printf("connected to %08lx:%d\n",addr,port);

		/*  ================================ */
		/*  inner loop runs the application  */
		/*  ================================ */
		for(;;) {

			/*  get one character, blocking (or poll with telnet_poll) */
			status = telnet_get(t,&ch,1);
			if (status == TELNET_LOSTCOMM) {
				/*  lost connection, break to outer loop and try to reconnect */
				printf("lost connection 1\n");
				break;
			}
			
			/** got a character, do something with it */

			/*  write something out in printf syntax */
			status = telnet_printf(t,"\n\rreceived a character : %c\n\r",ch);

			/*  write a string */
			status = telnet_puts(t,"hello world\n\r");

			/*  you can check status on output functions, but it isn't necessary. */
			/*  the loss of connection is always detected on the telnet_get or telnet_poll call */
		}

		/*  close the client connection */
		telnet_disconnect(t);
	}