Telnet Connection Using .net

Currently, our office uses telnet to request an external server. The procedure is something like this.

  • Connect - telnet opent 128 ........ 25000
  • Request - we insert the request, and then press alt + 019
  • Answer. We get the answer in the form of text in the telnet window.

So, I am trying to automate these requests using a C # application. My code is as follows

Connection first. (With no exceptions)

SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); String szIPSelected = txtIPAddress.Text; String szPort = txtPort.Text; int alPort = System.Convert.ToInt16(szPort, 10); System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected); System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort); SocketClient.Connect(remoteEndPoint); 

Then I submit the request (no exceptions)

  string data ="some query"; byte[] byData = System.Text.Encoding.ASCII.GetBytes(data); SocketClient.Send(byData); 

Then i try to get an answer

  byte[] buffer = new byte[10]; Receive(SocketClient, buffer, 0, buffer.Length, 10000); string str = Encoding.ASCII.GetString(buffer, 0, buffer.Length); txtDataRx.Text = str; public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout) { int startTickCount = Environment.TickCount; int received = 0; // how many bytes is already received do { if (Environment.TickCount > startTickCount + timeout) throw new Exception("Timeout."); try { received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None); } catch (SocketException ex) { if (ex.SocketErrorCode == SocketError.WouldBlock || ex.SocketErrorCode == SocketError.IOPending || ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable) { // socket buffer is probably empty, wait and try again Thread.Sleep(30); } else throw ex; // any serious error occurr } } while (received < size); } 

Every time I try to get a response, I get a β€œforce connection closed by the remote host”, if telnet is open and sends the same request, I immediately get a response

Any ideas or suggestions?

+4
source share
3 answers

Based on the exchange of comments between you and me, it seems to you that you need to add the Ascii 19 (0x13) code at the end of your request.

+5
source

In general, problems of this kind can be easily resolved using a network analysis tool (sniffer) such as Wireshark .

In particular, the telnet protocol includes the negotiation phase at the start of the session. I assume that if you ignore this, the owner will be unhappy. Using Wireshark with a successful telnet connection will show you what you are missing.

+2
source

The following is an example telnet library along with a program that uses it to log into a Cisco router and download the IOS configuration.

http://www.xpresslearn.com/networking/code/csharp-telnet-client

+1
source

Source: https://habr.com/ru/post/1310876/


All Articles