R – Visual Studio 2008 Vista Socket Problem

socketsvisual-studio-2008windows-server-2008

Hey there, I am trying to use a port checking program written in Visual Studio 2008 using the 3.5 SP 1 .Net Framework, and I seem to have a problem using my program on Vista based OS's (in this case the actual OS is Windows 2008 Server (both 32 and 64 bit machines)) while it does however work fine on XP machines. I am not entirely sure what the problem is, but I get a System.NotSupportedException. Any ideas on how I can change the following code (or preferably the machine configuration) to allow for this type of port checking?

    static bool IsPortOpen(int portNumber)
    {
        bool isOpen = false;
        IPAddress ip = (IPAddress)Dns.GetHostAddresses("localhost")[0];
        Socket s = null;

        try
        {
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, 
                 ProtocolType.Tcp))

            s.Connect(ip, portNumber);

            // Port is in use and connection is successful
            if (s.Connected == true)
            {
                isOpen = false;
            }
        }
        catch (SocketException exception)
        {
            // http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx
            if (exception.ErrorCode == 10061)
            {
                isOpen = true;
            }
        }
        finally
        {
            if (s != null)
            {
                s.Close();
            }
        }

        return isOpen;
    }

Best Answer

Turns out the problem was:

Dns.GetHostAddresses("localhost");

Returns 2 IP Addresses on Windows 2008 Server. The first is "::1" and the second is the actual IP. If anyone knows why this is (since i can't make sense of the "::1" return) I'd appreciate it, otherwise, just grabbing the last IP of the list seems to work.