S
S
Spark1082019-08-29 07:01:09
C++ / C#
Spark108, 2019-08-29 07:01:09

How to connect to Telnet from C#?

I'm trying to connect to the Telnet server using the following code:

I must say right away that the code is not completed. I'm only concerned about the operation of the ReadTelnet method and TCPClient.

using System;
using System.Diagnostics;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Spark108.Asda
{
  class ReloadApp
  {
    private static void Main(string[] args)
    {
      new ReloadApp(args);
    }
    
    public ReloadApp(string[] args)
    {
      Console.Title = "Перезагрузка ИП-1";
      
      IPAddress host = IPAddress.Parse("127.0.0.1");
      int port = 23;
      string username = "admin";
      string password = "admin";
      string remoteHost = "127.0.0.1";
      long timeout = 1000;
      
      var xdoc = XDocument.Load("config.xml");
      var rootElement = xdoc.Root;
      
      foreach (var optionElement in rootElement.Elements("option"))
      {
        var nameAttr = optionElement.Attribute("name");
        var valueAttr = optionElement.Attribute("value");
        if (nameAttr == null || valueAttr == null)
          continue;
          
        switch (nameAttr.Value)
        {
          case "host":
            if (!IPAddress.TryParse(valueAttr.Value, out host))
              Console.WriteLine("Ошибка чтения параметра host.");
            break;
          case "username":
            username = valueAttr.Value;
            break;
          case "password":
            password = valueAttr.Value;
            break;
          case "remote_host":
            remoteHost = valueAttr.Value;
            break;
          case "timeout":
            if (!long.TryParse(valueAttr.Value, out timeout))
              Console.WriteLine("Ошибка чтения параметра timeout.");
            break;
          case "port":
            if (!int.TryParse(valueAttr.Value, out port))
              Console.WriteLine("Ошибка чтения параметра port.");
            break;	
          default: continue;
        }
      }
      
      var endPoint = new IPEndPoint(host, port);
      var client = new TcpClient();
      client.Connect(endPoint);
      
      var response = ReadTelnet(client, timeout, "login:");
      Console.WriteLine(response);
    
      Console.ReadLine();
    }
    
    private string ReadTelnet(TcpClient client, long timeout = 1000, string pattern = null)
    {
      for (long i = 0; i < timeout; i++)
      {
        NetworkStream stream = client.GetStream();
        
        // if (client.ReceiveBufferSize <= 0 || !stream.CanRead || !stream.DataAvailable)
        if (client.ReceiveBufferSize <= 0)
          continue;
          
        do
        {
          System.Threading.Thread.Sleep(10000);
          
          byte[] buffer = new byte[client.ReceiveBufferSize];
          int p = stream.Read(buffer, 0, client.ReceiveBufferSize);
          
          string response = Encoding.ASCII.GetString(buffer).Trim();
          Console.WriteLine(string.Format("{0}. {1}", i, response));
          //for (var j = 0; j < buffer.Length; j++)
          //	Console.Write(buffer[j]);
          
          if (response == "")
            continue;
            
          if (pattern != null)
          {
            Regex objToMatch = new Regex(pattern);
            if (objToMatch.IsMatch(response)) 
            {
               return response;
            }
          }
          
          return response;
        }
        while (stream.DataAvailable);
      }
      
      return null;
    }
    
    private string WriteTelnet(TcpClient client, string command, long timeout)
    {
      return ReadTelnet(client, timeout);
    }
  }
}


The whole point is that we take a Telnet server (let's say HK Telnet Server) for a connection test. We connect, read the data and get a completely normal hello message. those. everything is working.

Move on. The code is written to connect to a Telnet server that runs on WinCE. When I test on HK Server everything is fine, when I start testing on WinCE, I get the message "???" in response. and smiley. What's the catch?

At the same time, I note that the standard Windows 7 Telnet client connects and works normally with both servers.

Here's the problematic one:
5d674d9900035084640967.png

Here's the normal one:
5d674e01711c3172504620.png

UPD.. #1 Funny. I knock on FTP - the answer is normal. Telnet issues everything the same.
5d6773feb8ff7011421047.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#, 2019-08-29
@mindtester

When I test on HK Server everything is fine, when I start testing on WinCE, I get the message "???" in response. and smiley. What's the catch?
in response encoding

S
Sumor, 2019-08-29
@Sumor

Try instead
And another problem may be that the console in which you are executing is configured for a single-byte encoding, and you output unicode through Console.WriteLine.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question