0

I'm new with Telnet, and I need to write a small program in WPF (C#) which send and receive commands to a device via telnet.

Its starts by:

  1. sending command "telnet 192.168.0.50" (in order to connect to the device)
  2. Then sending "User" and "Password"
  3. Then starting to send and receive data to the device, and all that communication need to appears on a WPF log screen.

I have search on Google information on how to do it, but I didn't find something which was helpful for me.

I'm asking here because I'm helpless and I need some directions in order to starts from somewhere... I'll really appreciate your help.

Thank you.

Orionlk
  • 278
  • 2
  • 3
  • 17

2 Answers2

3

I've a GitHub project https://github.com/9swampy/Telnet/, also published as a NuGet dll https://www.nuget.org/packages/Telnet that would allow you to:

using (Client client = new Client(server.IPAddress.ToString(), server.Port, new System.Threading.CancellationToken()))
{
  await client.TryLoginAsync("username", "password", TimeoutMs);
  client.WriteLine("whatever command you want to send");
  string response = await client.TerminatedReadAsync(">", TimeSpan.FromMilliseconds(TimeoutMs));
}

That should allow you to achieve what you want in your application, and you can check out the GitHub if you want to see the code making it all work.

9swampy
  • 1,441
  • 14
  • 24
1

Roughly (and in VB but should be simple to convert to c#). You'll just need to add the bits to write the username and password to the stream

Dim Data As String
Dim reader As StreamReader = Nothing
Dim NsStream As NetworkStream = Nothing
dim address as IPAddress = IPAddress.Parse("192.168.0.50")
Dim ipe As New IPEndPoint(address, port)
Dim telnetSocket As New Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

telnetSocket.Connect(ipe)

 If (telnetSocket.Connected) Then
     Try
    
         'if is necessary to send a command
         'telnetSocket.Send(Encoding.ASCII.GetBytes("Command to execute"))

         NsStream = New NetworkStream(telnetSocket, True)
         reader = New StreamReader(NsStream)

         Do While (Not reader.EndOfStream)

             ' Read the line of data
              Data = reader.ReadLine()
             'Do whatever with data
         Loop
    
    Catch ex As Exception
           Msgbox(ex.message)
    Finally
            Try
                If reader IsNot Nothing Then
                    reader.Close()
                End If
            Catch ex As Exception
            End Try
            Try
                If NsStream IsNot Nothing Then
                    NsStream.Close()
                End If
            Catch ex As Exception
            End Try
        End Try

end if
elle0087
  • 840
  • 9
  • 23
user3910810
  • 234
  • 1
  • 6