SRC: “simple telnet server” in 20 lines “C++” code.
Actually these are 43 lines counting the blank lines.
Writing “simple telnet server” is a simple task. All you have to do is to spawn the OS shell and redirect its input and output through a socket to the telnet client. Nowadays telnet clients are even smart enough not to need telnet control character when they are unneeded. Anyway occasionally you may see junk characters on the console screen. These are telnet control characters that are not handled by our “simple telnet server”. Of course there is some/lot code you have to write around the real telnet core, that I have skipped. Like checking user/pass credentials, running the shell within the user context, handling telnet control characters etc.
So here comes the 20-line simple telnet server. It has no user check nor error handling. It listens on port 8023 and will spawn the default windows shell expanding ( GetEnvironmentVariable ) the "%COMSPEC%" environment variable. One thing that makes it simpler is that it directly assigns the client socket for stdin/stdout/stderr of the spawned shell. Note that we need to create the socket through the WSASocket function ( and not socket ) so that we could use the socket as handle.
If you play a bit with the program you will find that it can not handle applications like 'edit.com' and it will hang on command waiting for ctrl + c to terminate, such as 'more'.
It is due to the following facts:
1 - 'edit.com' writes 'directly' to the video memory ( using functions like WriteConsole ) So the output is not sent to the console output handle but directly displayed in the console screen buffer. And our simple server does not export the console screen buffer.
2 - the 'more' command terminates on ctrl + c, but in windows console world ctrl + c is not a character, but it is a signal/event. The CTRL_C_EVENT is generated by the system when the keys ctrl + c are pressed in a console window and the event is sent to the console process. If the event is not handled by custom ctrl handler( installed through SetConsoleCtrlHandler ) the console process is closed by its default ctrl handler. Using our redirected input we actually send the ctrl + c character (0x03) to the stdio handle, and the system does not generate CTRL_C_EVENT.
edit 24.Jan.2006: source fixed. thank you anonymous for spotting defects.
Wednesday, December 14, 2005
© 2002 - 2008 Kroum Grigorov