why does sending a disconnect message to socket listener on same PC sometimes fail? RRS feed

  • Question

  • I use the AcceptTcpClient method of the TcpListener class to listen on a PC for a socket connection.  Then in some shutdown code I use the IPEndPoint and Socket classes to connect to the port being listened on to send a disconnect message to the listener. This works most of the time. But if I start VPN on my PC my listener starts to listen on the VPN IP address and when the disconnect thread tries to connect to that port I get an error: "an attempt was made to access a socket in a way forbidden by its access permisions".

    why this error? I assume it has to do with VPN but do not understand why. 


    // the socket listener code:
          // TcpListener is listening on the given port...	
          Int32 port = 1234;
          TcpListener server = new TcpListener(localAddr, port);
          TcpClient client = null;
          client = server.AcceptTcpClient();
    // the connect to socket to disconnect code:
        public static Socket ConnectSocket(IPAddress Addr, int PortNx)
          Socket s = null;
          Socket tempSocket = null;
          IPEndPoint ipe = null;
          ipe = new IPEndPoint(Addr, PortNx);
          tempSocket =
              new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
          if (tempSocket.Connected)
            s = tempSocket;
          return s;
    // and the code that returns the local IP address:
        public static IPAddress GetLocalIpAddress()
          IPAddress localAddr = null;
          string hostName = Dns.GetHostName();
          IPHostEntry he = Dns.GetHostEntry(hostName);
          IPAddress[] addrs = he.AddressList;
          // get the ip4 address from the address list 
          foreach (IPAddress addr in addrs)
            if (addr.AddressFamily == AddressFamily.InterNetwork)
              if (addr.ToString().IndexOf("192.168") != -1)
                localAddr = addr;
          return localAddr;

    Thursday, August 29, 2013 7:09 PM


  • Also check if the following are true:
    1) Your firewall does not allow processes to listen on blocked ports. Please see the related article, for how to fix this.
    2) You are running a second VNC Server on your computer, that is already listening on the default VNC port (TCP 5900). This effectively means that your new VNC Server is unable to bind to the correct listening port.
    • Marked as answer by Steve Richter Tuesday, September 3, 2013 2:26 AM
    Friday, August 30, 2013 6:25 AM