Click here to Skip to main content
Click here to Skip to main content

Telnet server classes

By , 12 Jun 2001
 

Introduction

This article presents two classes: CTelnet and CTelnetSocket, and one global function: TelnetThread. Using the CTelnet class, you can access/control your application remotely using a Telnet client. The download contains the classes to use, and a program to demonstrate the use of the CTelnet class.

CTelnetSocket is a class that is used internally (using Winsock calls). The global TelnetThread function is started as a separate thread. This way your application can run and the TelnetThread does all the Telnet activity. You can register some callback functions which are called by the TelnetThread. Usage is very easy:

Instantiate the CTelnet class:

CTelnet telnet( "Welcome at my telnetserver\r\n"    // intro screen
          , "scott"                               // userid
          , "Enter userid:"                     // userid prompt
          , "tiger"                           // password
          , "Enter password: "              // password prompt
          , "Command >"                   // prompt to use
          , 23 );                       // port to run on

Say, you want a function to be called whenever a user types help. Create a help function like this:

CString help( const CString& sArg );        // help function prototype

// implementation of the help function
CString help( const CString& sArg )
{
    return "\r\nCurrently no commands are implemented\r\n";
}

So this function gets called whenever the user types help (Not case sensitive). It will send data to the client "Currently no commands are implemented". When the user types "help command", sArg will contain the value " command". The next step is to register this (callback) function:

telnet.registerFunction( help , "help" );

You can create as much callback functions as you like. It is also possible to write a callback function that is called whenever the user just presses "enter". Register the function, and leave the second argument empty ("").

The next step is to start the service.

telnet.start();

Now, a user can connect to your application, that's it... Please note that a separate thread is running your Telnet service. So your application can do whatever you want after the start method is called.

Stopping the Telnet server is done by the destructor, or by calling the method stop:

telnet.stop();

When the application is running, you have two methods available: write() and setPrompt(). With the write method, you can write data to the client connected. E.g. it can be used for sending trace data.

telnet.write( "this will be sent to the client connected" );

Please note that this method cannot be used by any of the callback functions (It is not needed anyway, see implementation of callback help function).

Another method that can be called when the Telnet server is running is: setPrompt, which sets the prompt which is presented to the client:

telnet.setPrompt( "Another prompt>" );

Please note that this method cannot be used by any of the callback functions.

Final remarks:

  • For every instantiation of the CTelnet class, only one client can connect, you can however instantiate as many instances of CTelnet as you like.
  • When sharing data between the application and the callback functions (e.g. global variables), make sure you do that thread safe (e.g. using Critical Sections). The sample program which comes with the project files should give an idea on how to do this.
  • Most methods give back a boolean, true means it succeeded, false means it did not succeed. Call getLastError() to get the error that occurred.
  • The Telnet client connected should not do a local echo because the server does that itself.
  • Only backspace is implemented as a text editor command.

Have fun!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

J.Hogendoorn
Netherlands Netherlands
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberAric Green22 Sep '11 - 18:50 
Didn't work...
GeneralMy vote of 5member(BlackBox) Ethical Hacker31 Oct '10 - 5:35 
Nice
GeneralDetected memory leaksmembernflx5 Mar '06 - 19:37 
Detected memory leaks!
Dumping objects ->
strcore.cpp(118) : {90} normal block at 0x003F4838, 18 bytes long.
Data: < tige> 01 00 00 00 05 00 00 00 05 00 00 00 74 69 67 65
strcore.cpp(118) : {84} normal block at 0x003F2D50, 18 bytes long.
Data: < scot> 01 00 00 00 05 00 00 00 05 00 00 00 73 63 6F 74
Object dump complete.
 
I'm a devloper
QuestionUNIX?memberjontemannen2 Feb '06 - 4:32 
Sniff | :^) I want to connect to a unix server. But this telnet Client does not work...
Is there a way of hot up this TelnetClient so it can talk with a UnixServer?
GeneralVery GoodmemberMasterGohan17 Jan '06 - 7:30 
The one thing that you should note though, is that alot of telnet clients (such as the Windows provided) will default to Echo Off.   This means that you'll get repeat characters (and a messed up password prompt) due to that we're not coded to handle the initial session negotiations...   Easiest way to resolve this is to send an "IAC WILL ECHO" to our clients.
 
You'd need something like follows added to the TelnetThread(void* telnet) function (just before you do the client authentication).
//==========================================================
// Send WILL ECHO
char buffer[]={255,251,1};
if (!tel->getTelnetSocket()->sendData(CString(buffer)))
{
     tel->getTelnetSocket()->closeClientSocket();
     continue;
}
//==========================================================
...
CString sUserId;
if (tel->getUserId().GetLength()!=0)
...
 
Easy as that.   Now the client gets the **** field displayed properly and no repeat entries from local keystroke handling.
 
Anyhow, many thanks!   Saved me significant time with a recent project.
QuestionRe: Very Goodmembergmt20016 Feb '07 - 9:20 
That helped me but how do i make the garble sent by that code NOT show up on the client console?
AnswerRe: Very GoodmemberIantLetoxx24 Mar '10 - 11:23 
I know it's quite late but maybe this is still useful for someone. To prevent the garbage to be displayed, it shouldn't be sent at all: the WILL ECHO char array must be zero-terminated in order to be recognized by CString.
Simply define the buffer like this:
 
unsigned char buffer[]={255,251,1,0};
GeneralTalking to Unixmemberpetetastic26 Jan '04 - 15:50 
Hi there,
 
Great job by the way. I've implemented your class into an MFC project, but when I try telnetting in from a Unix or Linux client, nothing works. The unix telnet client appears to be sending garbage characters, or different line returns, or something. At the very least, it's operating in line mode, where it only sends the data when enter has been pressed, instead of byte for byte. Is there any modification I could make to allow it to work with Unix clients?
 
Thanks,
 
Pete
AnswerRe: Talking to UnixmemberMerlinblack20 Feb '06 - 18:53 
I hit this trouble with the Cygwin telnet as well. As soon as you connect, hit the Escape char (usally Ctrl + ] ) and type at the telnet prompt:
 
telnet>mode character
 
and press enter.
 
Now continue to type the user name and password and it should work.
 
Nigel Atkinson
 
"Land a'hoy!" * CRASH * "I should av said that sooner eh?" - Eckles, The Goon Show
QuestionMFC implementation?memberJan7513 Dec '02 - 0:02 
Hello all!
 
I just startet to implement these classes in my MFC application, but this doesn't work!! Why not? I included every headerfile the author did....
 
Has anyone an idea?
 
Thansk fo help,
 
Greetings Jan

AnswerRe: MFC implementation?memberMasterGohan17 Jan '06 - 7:42 
Though it may be late for a reply..   Doesn't mean that nobody else has this question...
 
The two points that you're probably getting compiler errors on are the following:
 
using namespace std;   // Error claiming an invalid namespace...
&
typedef vector<callBackFunction> callbackVector; // Error claiming invalid definition of "vector"...
 
Make the following changes, and that should compile without errors.
 
#include <string>
using namespace std;
...
#include <vector>
typedef vector<callBackFunction> callbackVector;
QuestionHow can we capture the data into a buffer in response to a command send to a test system using this Telnet ClassmemberThirumalesh Thirumala13 Dec '01 - 11:30 
Same as the SubjectMad | :mad:
 
Thiru
GeneralBug? - Cannot disconnect then reconnectmemberJeff Hansen18 Nov '01 - 18:17 
The classes are easy to work with although I did discover two problems.
 
First was a flaw using CreateThread() under win98;
 
// m_hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)TelnetThread, this , NULL, NULL); // NT only
unsigned long nDummy;
m_hThread = CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)TelnetThread, this , NULL, &nDummy); // jmh 2001.11.17 - nDummy for win98
 
Second was that I could could not disconnect and reconnect after a log on.
 
A fix in TelnetThread() goes like so;
 
// handle commands
CString sCommand;
if ( !tel->getTelnetSocket()->waitForData( sCommand ) )
{
tel->getTelnetSocket()->closeClientSocket();
// continue; // jmh 2001.11.17 - No good
break; // jmh 2001.11.17 - On recv() errors, Get Out.
}
 

QuestionTelnet Client?member-= Matt Newman =-17 Nov '01 - 13:28 
Does anyone have a class for a Telnet Client? Win XP came with a console client and can't stand it.
 

-Matt Newman
-Matt Newman


AnswerRe: Telnet Client?memberCyprus27 Nov '01 - 9:46 
I have a Telnet client, it's functional, I guess... It compiles at least. I haven't really gotten a chance to play with it much.
I don't know where I got it, otherwise I'd stick up the URL. If you want it drop me an e-mail at matth@usiw.net. I'll send you a copy of it.

 
Cyprus
GeneralRe: Telnet Client?memberMatt Newman28 Nov '01 - 11:29 
I found one but I don't really need it right now. Stupid Gateway decided to sell me parts the didn't have so now I have basically no computer. But If I need it I'll let you know.
 

-Matt Newman
-Matt Newman


GeneralRe: Telnet Client?memberHanphy18 May '03 - 22:13 
Wink | ;) I'd need one, if I could, thank you!
 
hanphy_cai@hotmail.com

GeneralRe: Telnet Client?membermohammad arif22 Oct '03 - 18:21 
Hi,
I also need telnet client if u have plz send me on
 
arif_alig@hotmail.comOMG | :OMG:
GeneralRe: Telnet Client?sussAnonymous14 Mar '04 - 10:32 
Check out PUTTY - its great and free (it also supports SSH)

GeneralRe: Telnet Client?membermarfemag30 May '04 - 12:43 
Yes, PUTTY is great. You can download the source code here. Wink | ;)
GeneralRe: Telnet Client?memberMerlinblack20 Feb '06 - 18:57 
HyperTerminal works OK too, and it comes with Windows.
 
Nigel Atkinson
 
"Land a'hoy!" * CRASH * "I should av said that sooner eh?" - Eckles, The Goon Show
GeneralRe: Telnet Client?memberrushivyas17 Aug '10 - 8:27 
hi cyprus i hav taken up the project of developing a small telnet server so it would really be very kind of ayou if u can help.
 
thank you
GeneralRe: Telnet Client?memberrushivyas17 Aug '10 - 8:30 
hey i am working for telnet SERVER......
 
Plz help
 
email: rushivyas263@gmail.com
AnswerRe: Telnet Client?memberliwenhaosuper13 Feb '11 - 16:07 
hi,thank you for your hard work and I need a client code now ,for liwenhaosuper@126.com
GeneralRe: Where to put your server name?member-= Matt Newman =-17 Nov '01 - 13:21 
I don't know much about Telnet but I don't think you need a server name/
 

-Matt Newman
-Matt Newman


GeneralStraight MFC telnet server implementationmemberAnonymous16 Aug '01 - 4:28 
Straight MFC telnet server implementation here:
http://home.worldonline.dk/~troels_k/code
QuestionEducated ?memberkoos k20 Jun '01 - 19:05 
Seems you picked up some techniques during your stay with us Smile | :) (Fenestrae B.V. Netherlands) . Nowadays we prefer use of map iso vector.
 

kokl@work
AnswerRe: Educated ?memberHogendoorn23 Jun '01 - 11:16 
Hmm, guess you got a point with that...
Cry | :((
Plse note that not all techniques were learned during my stay, check it out: "source code comments" Cool | :cool:
 


GeneralRe: Educated ?memberAnonymous11 Aug '01 - 2:36 
Confused | :confused:

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 13 Jun 2001
Article Copyright 2001 by J.Hogendoorn
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid