none
What am I doing wrong? RRS feed

  • Question

  • Hi all,

    I haven't programmed much for 20+ years and am trying to get into c#.  I have a piece of network code that works fine as a console app, but when I run it in a form app (triggered by a button press), I get this weird error I can't find much about in my situation.  Basically I have a little remote device that responds with the temperature at its location on port 9999 and I am trying to read the value:

    So this WORKS

    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                TcpClient MyTCPClient = new TcpClient();
                Console.WriteLine("Connecting.....");

                MyTCPClient.Connect("192.168.0.174", 9999);
                StreamReader sr = new StreamReader(MyTCPClient.GetStream());
                Console.WriteLine("Connected");
                try
                {
                    string data = sr.ReadLine();
                    while (data != null)
                    {
                        Console.WriteLine(data);
                        data = sr.ReadLine();
                    }
                    MyTCPClient.Close();
                }
                catch (Exception e)
                { }
                Console.Read();
            }
        }
    }

    However when I put the code into a form and button it doesn't.  I have tried it as a function and directly in the button function and get the same error.  The code is slightly different as I have been trying different things to get it to work but the error is only when I try to open the TcpClient connection.

    Code that doesn't work:

            private void BtnUpdate_Click(object sender, RoutedEventArgs e)
            {
                string clientIP = "192.168.0.174";
                displayTemp.Text = GetTemp(clientIP, 9999);
            }

            private string GetTemp(string ipAdd, int port)
            {
                TcpClient tcpClient = new TcpClient(ipAdd, port);
                string myData = "";
                StreamReader sr = new StreamReader(tcpClient.GetStream());
                try
                {
                    myData = sr.ReadLine();
                    while (myData != null)
                    {
                        myData += sr.ReadLine();
                    }
                    tcpClient.Close();
                }
                catch (Exception IgnoreException)
                {
                    tcpClient.Close();
                    return myData;
                }
                return myData;
            }

    The error I get (at runtime, not compile/build) is on this line

               TcpClient tcpClient = new TcpClient(ipAdd, port);

    and is:

    System.Net.Internals.SocketExceptionFactory.ExtendedSocketException: 'An attempt was made to access a socket in a way forbidden by its access permissions 192.168.0.174:9999'

    It makes me think that the function doesn't have permission to the library to open the connection or something.

    What rookie mistake am I making?

    Cheers and thanks for any help

    Apologies if I have broken any etiquette rules with this post

    Guy

    Thursday, January 4, 2018 1:38 PM

Answers

  • OK, problem solved!

    I found that I needed to enable :

    Application.appxmanifest / Capabilities / Private Networks (Client & Server)

    Ahhhh!  But this is how I tend to learn, trials and tribulations!

    Thanks all for your time and effort in trying to help

    Guy

    • Marked as answer by GB_Downunder Friday, January 5, 2018 1:27 AM
    Friday, January 5, 2018 1:04 AM

All replies

  • Hi Guy,

    Try running your IDE as an Administrator.

    Kind regards

    Ronald Mariah

    Thursday, January 4, 2018 2:54 PM
  • Hi Ronald,

    Unfortunately that didn't fix the issue :(

    Guy

    Thursday, January 4, 2018 2:59 PM
  • Hi!

    I don't see a "Connect" calling in the second  part of your code. Please, try this:

        private string GetTemp(string ipAdd, int port) {
    
          TcpClient tcpClient = new TcpClient();
          tcpClient.Connect(ipAdd, port); // ----------------------- connect here
          string myData = "";
          StreamReader sr = new StreamReader(tcpClient.GetStream());
          try {
            myData = sr.ReadLine();
            while (myData != null) {
              myData += sr.ReadLine();
            }
            tcpClient.Close();
          }
          catch (Exception IgnoreException) {
            tcpClient.Close();
            return myData;
          }
          return myData;
        }
    

    Thursday, January 4, 2018 3:09 PM
  • You don't have try/catch on that line, correct? The first thing to do when you get an exception you don't understand is to get look at everything in the exception. If you are debugging the program then the debugger is probably showing you everything in the exception.

    Also for complex systems such as networking and databases there is often additional ways to get exception information. Look at TcpClient Constructor (String, Int32). It says:

    System_CAPS_noteNote

    If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation in MSDN for a detailed description of the error.

    System_CAPS_noteNote

    This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.

    Have you tried that? Hopefully you don't need to do the network trace but that might be necessary. After doing all that post the results and ask for help if you need it.



    Sam Hobbs
    SimpleSamples.Info

    Thursday, January 4, 2018 9:38 PM
  • Hi Oleg,

    I initially tried it that way and get the same error on the tcpClient.Connect(ipAdd, port); call.

    TcpClient tcpClient = new TcpClient(ipAdd, port); is just a shorter way of calling the connect.

    Thanks anyway.

    Guy

    Thursday, January 4, 2018 11:23 PM
  • Hi Sam,

    Thanks, I will give this a go and see if I can get more information about the issue this way.

    Cheers

    Guy

    Thursday, January 4, 2018 11:23 PM
  • Hi Sam,

    It would seen=m the debugger was already giving me all the info.  The Error code is 10013 which I could this:

    Permission denied.
    An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST). 

    Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.

    This is what has me stumped.  The call to open the tcpClient works fine in that first piece of code (console app, and I tested it again now).  All I did was to try to put that code into a form that executed it when I pressed a button rather than as just inline code that ran (as in a the console app).  There has to be something related to this that is causing the issue, not the command itself.  Something like the scope of an include or the like.

    This is a Universal Windows App, is there anything about that that could be causing the issue?

    Cheers

    Guy


    Thursday, January 4, 2018 11:54 PM
  • OK, problem solved!

    I found that I needed to enable :

    Application.appxmanifest / Capabilities / Private Networks (Client & Server)

    Ahhhh!  But this is how I tend to learn, trials and tribulations!

    Thanks all for your time and effort in trying to help

    Guy

    • Marked as answer by GB_Downunder Friday, January 5, 2018 1:27 AM
    Friday, January 5, 2018 1:04 AM
  • Did you use SocketException.ErrorCode to obtain the specific error code?

    Also, you should be doing it in a separate thread. That is probably not related to this question but it should be mentioned. I am not experienced with networking so I am not sure but since you are having problems it might be related to doing this in the main thread. Probably not but it would help to have the additional error code.



    Sam Hobbs
    SimpleSamples.Info

    Friday, January 5, 2018 1:26 AM
  • See above Sam :)

    It wasn't the code, as suspected as it worked in another solution, but a solution setting I didn't even know existed :(

    I agree on the threading etc, but at the moment this was just some test code for me to get started on actually reading the data itself.  The real app is another solution that is going to be running on a IOT Raspberry Pi and that's where I should be threading of course :)

    PS: The error code was in the normal exception handling, I didn't get the SocketException.ErrorCode up and going.  I actually thought that perhaps tcpClient wasn't supported under UWP so I was looking at other ways to do it and found the solution in a pre-requisite for coding Sockets (in a different way) so I thought I would try it in my code, and BAM, it stopped failing.

    In hindsight the error description makes sense, I hadn't given the UWP app the permission to open a port to a local IP, but my problem was I didn't know I needed to!

    Cheers

    Guy

    Friday, January 5, 2018 1:34 AM
  • This is a Universal Windows App, is there anything about that that could be causing the issue?


    Definitely. Probably. This question should be in the Developing Universal Windows apps forum; be sure to read Guide to posting: subject line tags. UWP is different. In UWP it is very easy to be hit with async/await problems. If there is a relevant sample for UWP then you must look at it because Microsoft documentation is often not good about important details.

    I don't know if it would be better to get this moved to the other forum or create a new question. If you create a new question then you can link to it from here.



    Sam Hobbs
    SimpleSamples.Info

    Friday, January 5, 2018 1:36 AM
  • That is logical, right?


    Sam Hobbs
    SimpleSamples.Info

    Friday, January 5, 2018 2:45 AM
  • That's why you need to put UWP questions in the appropriate forum. You should have at least said UWP in the beginning. It would have saved your time and my time.

    And people that volunteer to try to help others appreciate it if you do as much as you can first. Gathering all the error information possible and doing searches and doing other things can easily solve the problem for you without asking questions. If you ask a question then it helps to have as much of the error information  as possible.

    I am experienced with UWP but not enough to think of the permissions immediately. The developers more experienced with UWP would be on the problem in a blink of an eye.



    Sam Hobbs
    SimpleSamples.Info

    Friday, January 5, 2018 2:53 AM
  • Hindsight is a beautiful thing, however this is a Visual C# forum so while you might now suggest a better group to have posted too knowing the resolution, it was not necessarily the wrong group to post too, given I am coding in C# in Visual Studio.  This group doesn't have any specific app type, and at the start of the problem, I had no idea it was a UWP problem.

    Guy


    Friday, January 5, 2018 3:06 AM
  • Then if it is a UWP application then post in the UWP forum. At least say it is UWP. You must do that much.


    Sam Hobbs
    SimpleSamples.Info

    Friday, January 5, 2018 6:26 AM
  • I'm so sorry that I wasted your time, but perhaps you should re-read my first post where I made it abundantly clear that I haven't programmed much for 20+ years so you might consider in that that I didn't exactly get the importance of the difference between a UWP app and other apps.  In fact I even made the mistake of just calling it a 'Form App' because it has the look of a form.  Only later when I realised the difference and importance did I clarify it as a 'UWP app'.
    Friday, January 5, 2018 7:41 AM