none
Connecting to PABX using MinimalisticTelnet throwing Socket Exceptions RRS feed

  • Question

  • Hello, I have used MinimalisticTlenet t create an application to connect to a Panasonic NS700 PABX and grab the phone data. 

    From Windows' own telnet client, I can connect fine. From my application, however, I get "System.Net.Sockets.SocketException::no connection could be made because the target machine actively refused it <PABX's external IP: port>

      at System.Net.Sockets.TcpClient..ctor(String hostname, Int32 port)  

    at TelnetToPABX.TelnetConnection..ctor(String Hostname, Int32 Port) in C:\Users\ME\Documents\Visual Studio 2017\Projects\TelnetToPABX\MinimalisticTelnet\TelnetInterface.cs:line 29

       at TelnetToPABX.Program.<Main>g__TalkToPABX0_0(<>c__DisplayClass0_1& , <>c__DisplayClass0_0& ) in C:\Users\ME\Documents\Visual Studio 2017\Projects\TelnetToPABX\MinimalisticTelnet\Program.cs:line 194
       at TelnetToPABX.Program.Main(String[] args) in C:\Users\MEDocuments\Visual Studio 2017\Projects\TelnetToPABX\MinimalisticTelnet\Program.cs:line 170"

    My code reads:

    TelnetInterface.cs
    ---------------------
    
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Sockets;
    
    namespace TelnetToPABX
    {
        enum Verbs {
            WILL = 251,
            WONT = 252,
            DO = 253,
            DONT = 254,
            IAC = 255
        }
    
        enum Options
        {
            SGA = 3
        }
    
        class TelnetConnection
        {
            TcpClient tcpSocket;
    
            int TimeOutMs = 500;
    
            public TelnetConnection(string Hostname, int Port)
            {
                tcpSocket = new TcpClient(Hostname, Port);
            }
    
    
            public string Login(string Username,string Password,int LoginTimeOutMs)
            {
                int oldTimeOutMs = TimeOutMs;
                TimeOutMs = LoginTimeOutMs;
                string s = Read();
                if (!s.TrimEnd().EndsWith("-"))
                    throw new Exception("Failed to connect : no login prompt");
                WriteLine(Username + Environment.NewLine);
    
                s += Read();
                if (!s.TrimEnd().EndsWith(":"))
                    throw new Exception("Failed to connect : no password prompt");
                WriteLine(Password + Environment.NewLine);
    
                s += Read();
                TimeOutMs = oldTimeOutMs;
                return s;
            }
    
            public void WriteLine(string cmd)
            {
                Write(cmd + "\r\n");     
                    }
    
            public void Write(string cmd)
            {
                if (!tcpSocket.Connected) return;
                byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(cmd.Replace("\0xFF","\0xFF\0xFF"));
                tcpSocket.GetStream().Write(buf, 0, buf.Length);
            }
    
            public string Read()
            {
                if (!tcpSocket.Connected) return null;
                StringBuilder sb=new StringBuilder();
                do
                {
                    ParseTelnet(sb);
                    System.Threading.Thread.Sleep(TimeOutMs);
                } while (tcpSocket.Available > 0);
                return sb.ToString();
            }
    
            public bool IsConnected
            {
                get { return tcpSocket.Connected; }
            }
    
    
            void ParseTelnet(StringBuilder sb)
            {
                while (tcpSocket.Available > 0)
                {
                    int input = tcpSocket.GetStream().ReadByte();
                    switch (input)
                    {
                        case -1 :
                            break;
                        case (int)Verbs.IAC:
                            // interpret as command
                            int inputverb = tcpSocket.GetStream().ReadByte();
                            if (inputverb == -1) break;
                            switch (inputverb)
                            {
                                case (int)Verbs.IAC: 
                                    //literal IAC = 255 escaped, so append char 255 to string
                                    sb.Append(inputverb);
                                    break;
                                case (int)Verbs.DO: 
                                case (int)Verbs.DONT:
                                case (int)Verbs.WILL:
                                case (int)Verbs.WONT:
                                    // reply to all commands with "WONT", unless it is SGA (suppress go ahead)
                                    int inputoption = tcpSocket.GetStream().ReadByte();
                                    if (inputoption == -1) break;
                                    tcpSocket.GetStream().WriteByte((byte)Verbs.IAC);
                                    if (inputoption == (int)Options.SGA )
                                        tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WILL:(byte)Verbs.DO); 
                                    else
                                        tcpSocket.GetStream().WriteByte(inputverb == (int)Verbs.DO ? (byte)Verbs.WONT : (byte)Verbs.DONT); 
                                    tcpSocket.GetStream().WriteByte((byte)inputoption);
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            sb.Append( (char)input );
                            break;
                    }
                }
            }
    
    
        }
    }

    Program.cs ________________ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; namespace TelnetToPABX { class Program { static void Main(string[] args) { string username = ""; string password = ""; string server = ""; int port = 0; Console.WriteLine("Locating Config file.."); XmlDocument doc = new XmlDocument(); if (File.Exists("pabx.config")) { doc.Load("pabx.config"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Config file found."); Console.ResetColor(); Console.WriteLine("Reading details from Config file..."); XmlNodeList PABXSettingS = doc.GetElementsByTagName("PABXSettings"); XmlNodeList logindetails = doc.GetElementsByTagName("login"); XmlNodeList serverdetails = doc.GetElementsByTagName("PABX"); int PABXFound = PABXSettingS.Count; int loginFound = logindetails.Count; int ServerFound = serverdetails.Count; if ((PABXFound == 0) || (loginFound == 0) || (ServerFound == 0)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Config file format incorrect. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Config file format correct. Using Content..."); Console.ResetColor(); foreach (XmlNode node in PABXSettingS) // for every individual booking found in the XML source.... { XmlNodeList logiN = doc.GetElementsByTagName("login"); // create a nodelist of the <login> nodes XmlNodeList PABx = doc.GetElementsByTagName("PABX"); // create a nodelist of the <PABX> nodes foreach (XmlNode lgn in logiN) { string uname = lgn.Attributes["uname"].Value; if (uname == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No username found in config in file. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } else { username = uname; } string pword = lgn.Attributes["pword"].Value; if (pword == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No password found in config in file. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } else { password = pword; } } foreach (XmlNode pbx in PABx) { string svr = pbx.Attributes["Server"].Value; if (svr == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No server found in config in file. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } else { server = svr; } string prt = pbx.Attributes["Port"].Value; if (prt == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("No port found in config in file. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } else { port = Convert.ToInt16(prt); } } } String path = Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\Documents\telnetoutput.txt"); Console.WriteLine("Testing to see if {0} is at end of port {1}", server, port); try { using (var client = new TcpClient()) { client.Connect(server, port); using (var stream = client.GetStream()) { using (var reader = new StreamReader(stream)) { string tcpresponce = reader.ReadLine(); if (tcpresponce == null) { failed(tcpresponce); } else { TalkToPABX(); } } } } //Methods void TalkToPABX() { System.IO.File.Delete(path); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Success.Found something on the end of port {0} on {1}", port, server); Console.ResetColor(); Console.WriteLine("Attempting Telnet communication with {0} on port {1} ", server, port); TelnetConnection tc = null; string disconnectClient = "false"; try { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Connected..."); Console.ResetColor(); tc = new TelnetConnection(server, port); Console.WriteLine("gethisfar"); string output = tc.Read(); //// while connected while ((tc.IsConnected) && disconnectClient == "false") { output = ""; Console.Write(tc.Read()); Console.WriteLine("Login in ..."); tc.Write(username + Environment.NewLine); output = tc.Read(); Console.Write(output); output = ""; Console.Write(tc.Read()); tc.Write(password + Environment.NewLine); output = tc.Read(); Console.Write(output); output = ""; Console.ReadLine(); // display server output Console.Write(output); System.IO.File.AppendAllText(path, output); output = "";

    disconnectClient = "true"; // need this else infinite loop } Console.WriteLine("Data received......."); } finally { Console.WriteLine("DISCONNECTING"); } } void failed(string tcpresponce) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Environment.NewLine + "Unable to make connection to the host. Error received reads {0}. Disconnecting and closing this interface.", tcpresponce); Console.ResetColor(); } } catch (System.Net.Sockets.SocketException msg) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Environment.NewLine + "The application has produced a SOCKET EXECPTION. Error reads:" + Environment.NewLine + msg); Console.ResetColor(); Console.ReadLine(); } catch (System.IO.IOException msg) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(Environment.NewLine + "The Host rejected the connection. Error reads:" + Environment.NewLine + msg); Console.ResetColor(); Console.ReadLine(); } } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Config file not found in same dir as app. Please review and fix. Press Return to close."); Console.ResetColor(); Console.ReadLine(); return; } } } }

    .. and it "fails" at                                 <g class="gr_ gr_364 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="364" id="364">tc</g> = new TelnetConnection(server, port);

    I have turned my FW off and added Port forwarding on my router (in case it was that), but I still get the same message.

    Can someone shed any light on this for me? What am I doing wrong?

    Thanks


    • Edited by G-Oker Monday, December 11, 2017 3:08 PM
    Monday, December 11, 2017 2:23 PM

Answers

  • hello G-Oker,

    Your code where it was worth to refer is

    tcpSocket = new TcpClient(Hostname, Port); 

    Your exception are thrown from there. "no connection could be made because the target machine actively refused itUsually "Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. The problem is no related to your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port, this may be because it is not running at all or because it is listening on a different port.

    https://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it

    I'm not sure why you connecting server via different port. I think this is the main cause of your issue.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by G-Oker Wednesday, April 18, 2018 8:40 AM
    Tuesday, December 12, 2017 7:30 AM
    Moderator

All replies

  • using Wireshark, when I try an connect via my application, I get

    when I telnet, I get

    So, If I am reading this correctly, a) my application is connecting via a different port (19733) to Telnet (19763)...could that be the problem? and if so, what can I do to fix it?

    Monday, December 11, 2017 3:47 PM
  • hello G-Oker,

    Your code where it was worth to refer is

    tcpSocket = new TcpClient(Hostname, Port); 

    Your exception are thrown from there. "no connection could be made because the target machine actively refused itUsually "Actively refused it" means that the host sent a reset instead of an ack when you tried to connect. The problem is no related to your code. Either there is a firewall blocking the connection or the process that is hosting the service is not listening on that port, this may be because it is not running at all or because it is listening on a different port.

    https://stackoverflow.com/questions/2972600/no-connection-could-be-made-because-the-target-machine-actively-refused-it

    I'm not sure why you connecting server via different port. I think this is the main cause of your issue.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by G-Oker Wednesday, April 18, 2018 8:40 AM
    Tuesday, December 12, 2017 7:30 AM
    Moderator
  • Friday, December 15, 2017 4:14 PM
  • Hello G-Oker,

    I'm glad the issues have been solved, congratulate to you. And you could close the thread by marking the helpful reply as answer, this will prompt Microsoft employees ignore the post has been already solved, and this also be beneficial to other community members reading this thread has the same situations. Thanks a lot.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 19, 2017 9:54 AM
    Moderator