views:

312

answers:

3

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;
    }
A: 

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.

MicroPirate
A: 

::1 is the IPv6 loopback address. Your code fails because you use AddressFamily.InterNetwork instead of AddressFamily.InternetWorkV6.

Vista+ has IPv6 running by default. It's a separate configuration option for XP/2003.

EricLaw -MSFT-
A: 

I believe there are two IP addresses returned on Windows 2008 Server because one is IPv4 and the other is the IPv6 address.

"When an empty string is passed as the host name, this method returns the IPv4 addresses of the local host for all operating systems except Windows Server 2003; for Windows Server 2003, both IPv4 and IPv6 addresses for the local host are returned." Src: http://msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx