Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. IndexOutOfRangeExceoption while parsing a Netstat process

IndexOutOfRangeExceoption while parsing a Netstat process

Scheduled Pinned Locked Moved C#
jsonquestion
20 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C CCodeNewbie

    Have added in a new exception to display s.length. Would you rather recommend

    if(Line.length = 0)?

    L Offline
    L Offline
    Luc Pattyn
    wrote on last edited by
    #6

    you already have an emptyOrNull test at the start, use that to exit the loop. and I tend to display the original inputs when things go wrong, and optionally also derived values. chances are NetStat occasionally emits a line you never expected! :)

    Luc Pattyn [My Articles] Nil Volentibus Arduum

    1 Reply Last reply
    0
    • C CCodeNewbie

      Hi, May I have some fresh eyes please? Under a Windows service running as LocalSystem, on a 60 second timed interval, I am running the following:

      //set & call process netstat -ano
      Process Ns = new Process();
      ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
      startInfo.Arguments = "-ano";
      startInfo.UseShellExecute = false;
      startInfo.RedirectStandardOutput = true;
      startInfo.CreateNoWindow = true;
      Ns.StartInfo = startInfo;
      Ns.Start();
      Ns.WaitForExit();
      for (int i = 0; i < 4; i++)
      Ns.StandardOutput.ReadLine();
      while (true)
      {
      string Line = (Ns.StandardOutput.ReadLine());
      if (!string.IsNullOrEmpty(Line))
      {
      //remove all spaces/padding/charactes so that only spaces remain between values
      Line = Line.Trim();
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(" ", " ");
      Line = Line.Replace(":", " ");
      Line = Line.Replace('\r', ' ');
      Line = Line.Replace('\n', ' ');
      string[] s = Line.Split(' ')
      //tcp protocol has 7 values, udp connections to external IP address have 7 values
      if (s.Length == 7)
      {
      //insns is a sqlcommand - this works faultlessly every time
      insns.Parameters["@Protocol"].Value = s[0];
      insns.Parameters["@LocalHost"].Value = s[1];
      insns.Parameters["@LocalPort"].Value = s[2];
      insns.Parameters["@RemoteHost"].Value = s[3];
      insns.Parameters["@RemotePort"].Value = s[4];
      insns.Parameters["@State"].Value = s[5];
      insns.Parameters["@PID"].Value = s[6];
      }
      else
      //non-connected udp ports have no 'state' thus they have only 6 values
      {
      insns.Parameters["@Protocol"].Value = s[0];
      insns.Parameters["@LocalHost"].Value = s[1];
      insns.Parameters["@LocalPort"].Value = s[2];
      insns.Parameters["@RemoteHost"].Value = s[3];
      insns.Parameters["@RemotePort"].Value = s[4];
      insns.Parameters["@State"].Value = "0";
      insns.Parameters["@PID"].Value = s[5];
      }
      //check for the end of the output
      if (Line == null)
      break;
      }
      //clear up
      Ns.Cl

      V Offline
      V Offline
      V 0
      wrote on last edited by
      #7

      Nothing to do with your question, but consider changing:

      string Line = (Ns.StandardOutput.ReadLine());

      to

      StringBuilder Line = new StringBuilder((Ns.StandardOutput.ReadLine()));

      and just call:

      Line.Replace(" ", " ");
      .... // rest here

      instead of

      Line = Line.Replace(" ", " ");
      ...//rest here

      Here the code is sequential and usage between string and StringBuilder is not that different, but if you do stringmanipulation in a loop, the performance difference can become huge. Just a tip.

      V.

      1 Reply Last reply
      0
      • L Lost User

        CCodeNewbie wrote:

        I am fairly sure that this is because the netstat never gets to .Close & .Dispose thus never receives an Exit signal so the .WaitForExit stays waiting. I am right in this assumption?

        I wouldn't pick it as the first suspect for an "index out of range" message.

        CCodeNewbie wrote:

        Can I track which index this is

        Did the exception come with a stack-trace? What is the content of "Exception.ToString()"?

        CCodeNewbie wrote:

        'On Error Resume Next' around it?

        Let's ignore that you mentioned this.

        string[] s = Line.Split(' ')
        //tcp protocol has 7 values, udp connections to external IP address have 7 values
        if (s.Length == 7)
        {
        //insns is a sqlcommand - this works faultlessly every time
        insns.Parameters["@Protocol"].Value = s[0];
        insns.Parameters["@LocalHost"].Value = s[1];
        insns.Parameters["@LocalPort"].Value = s[2];
        insns.Parameters["@RemoteHost"].Value = s[3];
        insns.Parameters["@RemotePort"].Value = s[4];
        insns.Parameters["@State"].Value = s[5];
        insns.Parameters["@PID"].Value = s[6];
        }
        elseif (s.Length == 6)
        //non-connected udp ports have no 'state' thus they have only 6 values
        {
        insns.Parameters["@Protocol"].Value = s[0];
        insns.Parameters["@LocalHost"].Value = s[1];
        insns.Parameters["@LocalPort"].Value = s[2];
        insns.Parameters["@RemoteHost"].Value = s[3];
        insns.Parameters["@RemotePort"].Value = s[4];
        insns.Parameters["@State"].Value = "0";
        insns.Parameters["@PID"].Value = s[5];
        }
        else
        {
        throw new Exception("This is where it probably goes boom");
        }

        Bastard Programmer from Hell :suss:

        C Offline
        C Offline
        CCodeNewbie
        wrote on last edited by
        #8

        Hi Eddy, Sorry I haven't got back to you sooner. Did what you suggested but now it makes even less sense:

        throw new Exception("failed " + s.Length + " : " + s + " : " + Line);

        results in failed 6 : System.String[] : UDP 0.0.0.0 445 * * 4 pardon my ignorance but why is it ignoring the

        if (s.Length == 6)

        instruction?

        L 1 Reply Last reply
        0
        • C CCodeNewbie

          Hi Eddy, Sorry I haven't got back to you sooner. Did what you suggested but now it makes even less sense:

          throw new Exception("failed " + s.Length + " : " + s + " : " + Line);

          results in failed 6 : System.String[] : UDP 0.0.0.0 445 * * 4 pardon my ignorance but why is it ignoring the

          if (s.Length == 6)

          instruction?

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #9

          CCodeNewbie wrote:

          pardon my ignorance but why is it ignoring the

          if (s.Length == 6)

          instruction?

          It shouldn't, if the string can be divided into six different words. The line that has been logged, would be broken down like this;

          1. UDP
          2. 0.0.0.0
          3. 445
          4. *
          5. *
          6. 4

          You can verify the result using the code below;

          foreach (string someWord in s)
          {
          System.Diagnostics.Debugger.WriteLine("'{0}'", someWord);
          }

          Also, can you post your (updated) code again?

          Bastard Programmer from Hell :suss:

          C 2 Replies Last reply
          0
          • L Lost User

            CCodeNewbie wrote:

            pardon my ignorance but why is it ignoring the

            if (s.Length == 6)

            instruction?

            It shouldn't, if the string can be divided into six different words. The line that has been logged, would be broken down like this;

            1. UDP
            2. 0.0.0.0
            3. 445
            4. *
            5. *
            6. 4

            You can verify the result using the code below;

            foreach (string someWord in s)
            {
            System.Diagnostics.Debugger.WriteLine("'{0}'", someWord);
            }

            Also, can you post your (updated) code again?

            Bastard Programmer from Hell :suss:

            C Offline
            C Offline
            CCodeNewbie
            wrote on last edited by
            #10

            Hi Eddy, Usually it does divide. "UDP 0.0.0.0:445 *:* 4" put through

            if (s.Length == 6)
            {
            insns.Parameters["@Protocol"].Value = s[0];
            insns.Parameters["@LocalHost"].Value = s[1];
            insns.Parameters["@LocalPort"].Value = s[2];
            insns.Parameters["@RemoteHost"].Value = s[3];
            insns.Parameters["@RemotePort"].Value = s[4];
            insns.Parameters["@State"].Value = "0";
            insns.Parameters["@PID"].Value = s[5];
            }

            becomes s[0]=UDP s[1]=0.0.0.0 s[2]=445 s[3]=* s[4]=* s[5]=0 s[6]=4 if I remove the line "insns.Parameters["@State"].Value = "0";" the output reports "Listening" even though there is no value in the netstat cmd-line output. Sorry this is taking a while, worked out I had to use System.Diagnostics.Debug.WriteLine instead of System.Diagnostics.Debugger.WriteLine So, I did

            Process Ns = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
            startInfo.Arguments = "-ano";
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardOutput = true;
            startInfo.CreateNoWindow = true;
            Ns.StartInfo = startInfo;
            Ns.Start();
            Ns.WaitForExit();
            for (int i = 0; i < 4; i++)
            Ns.StandardOutput.ReadLine();
            while (true)
            {
            Line = (Ns.StandardOutput.ReadLine());
            if (!string.IsNullOrEmpty(Line))
            {
            Line = Line.Trim();
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(" ", " ");
            Line = Line.Replace(":", " ");
            Line = Line.Replace('\r', ' ');
            Line = Line.Replace('\n', ' ');
            s = Line.Split(' ');
            if (s[0] == "TCP")
            {
            if (s[1] != "0.0.0.0")
            {
            insns.Parameters["@Tstamp"].Value = DateTime.Now;
            insns.Parameters["@SysID"].Value = SID;
            insns.Parameters["@Protocol"].Value = s[0];
            insns.Parameters["@LocalHost"].Value = s[1];
            insns.Parameters["@LocalPort"].Value = s[2];
            insns.Parameters["@RemoteHost"].Value = s[3];
            insns.Parameters["@RemotePort"].Value = s[4];
            insns.Parameters["@State"].Value =

            L 1 Reply Last reply
            0
            • C CCodeNewbie

              Hi Eddy, Usually it does divide. "UDP 0.0.0.0:445 *:* 4" put through

              if (s.Length == 6)
              {
              insns.Parameters["@Protocol"].Value = s[0];
              insns.Parameters["@LocalHost"].Value = s[1];
              insns.Parameters["@LocalPort"].Value = s[2];
              insns.Parameters["@RemoteHost"].Value = s[3];
              insns.Parameters["@RemotePort"].Value = s[4];
              insns.Parameters["@State"].Value = "0";
              insns.Parameters["@PID"].Value = s[5];
              }

              becomes s[0]=UDP s[1]=0.0.0.0 s[2]=445 s[3]=* s[4]=* s[5]=0 s[6]=4 if I remove the line "insns.Parameters["@State"].Value = "0";" the output reports "Listening" even though there is no value in the netstat cmd-line output. Sorry this is taking a while, worked out I had to use System.Diagnostics.Debug.WriteLine instead of System.Diagnostics.Debugger.WriteLine So, I did

              Process Ns = new Process();
              ProcessStartInfo startInfo = new ProcessStartInfo("netstat");
              startInfo.Arguments = "-ano";
              startInfo.UseShellExecute = false;
              startInfo.RedirectStandardOutput = true;
              startInfo.CreateNoWindow = true;
              Ns.StartInfo = startInfo;
              Ns.Start();
              Ns.WaitForExit();
              for (int i = 0; i < 4; i++)
              Ns.StandardOutput.ReadLine();
              while (true)
              {
              Line = (Ns.StandardOutput.ReadLine());
              if (!string.IsNullOrEmpty(Line))
              {
              Line = Line.Trim();
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(" ", " ");
              Line = Line.Replace(":", " ");
              Line = Line.Replace('\r', ' ');
              Line = Line.Replace('\n', ' ');
              s = Line.Split(' ');
              if (s[0] == "TCP")
              {
              if (s[1] != "0.0.0.0")
              {
              insns.Parameters["@Tstamp"].Value = DateTime.Now;
              insns.Parameters["@SysID"].Value = SID;
              insns.Parameters["@Protocol"].Value = s[0];
              insns.Parameters["@LocalHost"].Value = s[1];
              insns.Parameters["@LocalPort"].Value = s[2];
              insns.Parameters["@RemoteHost"].Value = s[3];
              insns.Parameters["@RemotePort"].Value = s[4];
              insns.Parameters["@State"].Value =

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #11

              CCodeNewbie wrote:

              becomes
              s[0]=UDP s[1]=0.0.0.0 s[2]=445 s[3]=* s[4]=* s[5]=0 s[6]=4

              That's strange; if s[] contains six elements, how did we get seven items here? s[5] should be 4 IMHO, and s[6] shouldn't be there.

              CCodeNewbie wrote:

              worked out I had to use System.Diagnostics.Debug.WriteLine instead of System.Diagnostics.Debugger.WriteLine

              Aw, my apologies; I tend to mix them up outside of the IDE. It should list all the words in the array in the output-window of Visual Studio.

              CCodeNewbie wrote:

              when the timer triggered my CPU ramped up to 99% usage by my app and I had to End-Task it. Nothing was written to the Output or the Event log.

              Could it be that it's reading a lot of empty lines?

              while (true)
              {
              Line = (Ns.StandardOutput.ReadLine());
              if (!string.IsNullOrEmpty(Line))

              Bastard Programmer from Hell :suss:

              C 1 Reply Last reply
              0
              • L Lost User

                CCodeNewbie wrote:

                pardon my ignorance but why is it ignoring the

                if (s.Length == 6)

                instruction?

                It shouldn't, if the string can be divided into six different words. The line that has been logged, would be broken down like this;

                1. UDP
                2. 0.0.0.0
                3. 445
                4. *
                5. *
                6. 4

                You can verify the result using the code below;

                foreach (string someWord in s)
                {
                System.Diagnostics.Debugger.WriteLine("'{0}'", someWord);
                }

                Also, can you post your (updated) code again?

                Bastard Programmer from Hell :suss:

                C Offline
                C Offline
                CCodeNewbie
                wrote on last edited by
                #12

                tried

                if (s.Length == 6)
                {
                insns.Parameters["@Tstamp"].Value = DateTime.Now;
                insns.Parameters["@SysID"].Value = SID;
                insns.Parameters["@Protocol"].Value = s[0];
                insns.Parameters["@LocalHost"].Value = s[1];
                insns.Parameters["@LocalPort"].Value = s[2];
                insns.Parameters["@RemoteHost"].Value = s[3];
                insns.Parameters["@RemotePort"].Value = s[4];
                insns.Parameters["@State"].Value = string.Empty;
                insns.Parameters["@PID"].Value = s[5];
                NSInfo.Open();
                insns.ExecuteNonQuery();
                NSInfo.Close()
                };

                same thing - service starts, netstat launches, CPU 99%

                1 Reply Last reply
                0
                • L Lost User

                  CCodeNewbie wrote:

                  becomes
                  s[0]=UDP s[1]=0.0.0.0 s[2]=445 s[3]=* s[4]=* s[5]=0 s[6]=4

                  That's strange; if s[] contains six elements, how did we get seven items here? s[5] should be 4 IMHO, and s[6] shouldn't be there.

                  CCodeNewbie wrote:

                  worked out I had to use System.Diagnostics.Debug.WriteLine instead of System.Diagnostics.Debugger.WriteLine

                  Aw, my apologies; I tend to mix them up outside of the IDE. It should list all the words in the array in the output-window of Visual Studio.

                  CCodeNewbie wrote:

                  when the timer triggered my CPU ramped up to 99% usage by my app and I had to End-Task it. Nothing was written to the Output or the Event log.

                  Could it be that it's reading a lot of empty lines?

                  while (true)
                  {
                  Line = (Ns.StandardOutput.ReadLine());
                  if (!string.IsNullOrEmpty(Line))

                  Bastard Programmer from Hell :suss:

                  C Offline
                  C Offline
                  CCodeNewbie
                  wrote on last edited by
                  #13

                  from a cmd-line netstat -ano you can see that the field usually used by "State" tends to be empty under the UDP protocol unless there is some stream coming in in which case it will show "Established" or whatever. Because I am writing the values to a SQL table I need to keep s[6] in the PID column.

                  Quote:

                  Could it be that it's reading a lot of empty lines?

                  don't think so, usually it works fine until it hits a null/empty value somewhere in the s[] array. What would be ideal is a way of saying: if (s[whatever].isNullorEmpty){s[whatever] = "0";}

                  L 1 Reply Last reply
                  0
                  • C CCodeNewbie

                    from a cmd-line netstat -ano you can see that the field usually used by "State" tends to be empty under the UDP protocol unless there is some stream coming in in which case it will show "Established" or whatever. Because I am writing the values to a SQL table I need to keep s[6] in the PID column.

                    Quote:

                    Could it be that it's reading a lot of empty lines?

                    don't think so, usually it works fine until it hits a null/empty value somewhere in the s[] array. What would be ideal is a way of saying: if (s[whatever].isNullorEmpty){s[whatever] = "0";}

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #14

                    Select the menu "Debug" and then "Toggle Breakpoint", and use F10 to step through your code.

                    CCodeNewbie wrote:

                    What would be ideal is a way of saying:

                    Something like this?

                    string FetchFromArray(string[] source, int idx)
                    {
                    if (idx <= source.Length)
                    return source[idx];
                    else
                    return String.Empty;
                    }
                    public Form1()
                    {
                    InitializeComponent();
                    string[] s = "Hello world from Mars!".Split(' ');
                    Text = FetchFromArray(s, 7);
                    }

                    Bastard Programmer from Hell :suss:

                    C 2 Replies Last reply
                    0
                    • L Lost User

                      Select the menu "Debug" and then "Toggle Breakpoint", and use F10 to step through your code.

                      CCodeNewbie wrote:

                      What would be ideal is a way of saying:

                      Something like this?

                      string FetchFromArray(string[] source, int idx)
                      {
                      if (idx <= source.Length)
                      return source[idx];
                      else
                      return String.Empty;
                      }
                      public Form1()
                      {
                      InitializeComponent();
                      string[] s = "Hello world from Mars!".Split(' ');
                      Text = FetchFromArray(s, 7);
                      }

                      Bastard Programmer from Hell :suss:

                      C Offline
                      C Offline
                      CCodeNewbie
                      wrote on last edited by
                      #15

                      Trying to work out why mu CPU is going mad at the moment, I'll get back to this in a bit..

                      1 Reply Last reply
                      0
                      • L Lost User

                        Select the menu "Debug" and then "Toggle Breakpoint", and use F10 to step through your code.

                        CCodeNewbie wrote:

                        What would be ideal is a way of saying:

                        Something like this?

                        string FetchFromArray(string[] source, int idx)
                        {
                        if (idx <= source.Length)
                        return source[idx];
                        else
                        return String.Empty;
                        }
                        public Form1()
                        {
                        InitializeComponent();
                        string[] s = "Hello world from Mars!".Split(' ');
                        Text = FetchFromArray(s, 7);
                        }

                        Bastard Programmer from Hell :suss:

                        C Offline
                        C Offline
                        CCodeNewbie
                        wrote on last edited by
                        #16

                        Sorted out the CPU thing, and so far haven't had any exceptions (after about an hour of testing). So far so good although I do need to ass a couple of modules back into the service. Now for my next problem...http://www.codeproject.com/Messages/4214946/Re-Getting-values-from-tasklist-exe-v-update.aspx[^]

                        L 1 Reply Last reply
                        0
                        • C CCodeNewbie

                          Sorted out the CPU thing, and so far haven't had any exceptions (after about an hour of testing). So far so good although I do need to ass a couple of modules back into the service. Now for my next problem...http://www.codeproject.com/Messages/4214946/Re-Getting-values-from-tasklist-exe-v-update.aspx[^]

                          L Offline
                          L Offline
                          Lost User
                          wrote on last edited by
                          #17

                          Nice :) I was kind of busy with a very tasty rabbit :D

                          Bastard Programmer from Hell :suss:

                          C 1 Reply Last reply
                          0
                          • L Lost User

                            Nice :) I was kind of busy with a very tasty rabbit :D

                            Bastard Programmer from Hell :suss:

                            C Offline
                            C Offline
                            CCodeNewbie
                            wrote on last edited by
                            #18

                            Had a leg of lamb myself, roast potatoes, roast butternut, sweetish-sharp gravy... All good...

                            L 1 Reply Last reply
                            0
                            • C CCodeNewbie

                              Had a leg of lamb myself, roast potatoes, roast butternut, sweetish-sharp gravy... All good...

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #19

                              CCodeNewbie wrote:

                              Had a leg of lamb myself, roast potatoes, roast butternut, sweetish-sharp gravy... All good...

                              Sounds like an equal festive meal - today, life's good :D

                              Bastard Programmer from Hell :suss:

                              C 1 Reply Last reply
                              0
                              • L Lost User

                                CCodeNewbie wrote:

                                Had a leg of lamb myself, roast potatoes, roast butternut, sweetish-sharp gravy... All good...

                                Sounds like an equal festive meal - today, life's good :D

                                Bastard Programmer from Hell :suss:

                                C Offline
                                C Offline
                                CCodeNewbie
                                wrote on last edited by
                                #20

                                tell it like it is fellow gastronaut... and thanks for looking in on the other thing that's making me tear my hair out... Why do so may seemingly simple things have to be so complicated...

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups