Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Is there a better way to determine if a tcp port is available for use?

Options
  • 01-10-2012 9:35pm
    #1
    Registered Users Posts: 7,501 ✭✭✭


    Currently im using the below method to determine if a port on my local machine is available for use.

    It seems to work fine but its based on the assumption that the exception thrown is because the port is not in use.

    Is there a better way?

    private bool portAvailable(int port)
    {
    try
    {                
       Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       s.Connect(IPAddress.Loopback, port);
       s.Disconnect(true);
       return false;
    }
    
    catch
    {                
       return true;
    } 
    }
    


Comments

  • Registered Users Posts: 527 ✭✭✭Sean^DCT4


    using System.Net.NetworkInformation;
    
    private bool portAvailable(int port) 
    {
        IPGlobalProperties ipProps = IPGlobalProperties.GetIPGlobalProperties();
        IPEndPoint[] ipEndPoints = ipProps.GetActiveTcpListeners();
    
        foreach (IPEndPoint ep in ipEndPoints) {
            if (ep.Port == port) {
                return false;
            }
        }
    
        return true;
    }
    


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    That only reports on active connections. If a port is listening with no.connection this won't work.


  • Registered Users Posts: 1,994 ✭✭✭lynchie


    If you use the GetTcpTable2() method it will return the following
    typedef [COLOR=Blue]struct[/COLOR] _MIB_TCPROW2 
    {   
    DWORD                        dwState;   
    DWORD                        dwLocalAddr;  
    DWORD                        dwLocalPort;  
    DWORD                        dwRemoteAddr;   
    DWORD                        dwRemotePort;   
    DWORD                        dwOwningPid;   
    TCP_CONNECTION_OFFLOAD_STATE dwOffloadState;
     } MIB_TCPROW2, *PMIB_TCPROW2; 
    
    Its not c# but you should be able to interface with it


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    lynchie wrote: »
    If you use the GetTcpTable2() method it will return the following
    typedef [COLOR=Blue]struct[/COLOR] _MIB_TCPROW2 
    {   
    DWORD                        dwState;   
    DWORD                        dwLocalAddr;  
    DWORD                        dwLocalPort;  
    DWORD                        dwRemoteAddr;   
    DWORD                        dwRemotePort;   
    DWORD                        dwOwningPid;   
    TCP_CONNECTION_OFFLOAD_STATE dwOffloadState;
     } MIB_TCPROW2, *PMIB_TCPROW2; 
    
    Its not c# but you should be able to interface with it

    Could be good but according to msdn its minimum supported OS is Vista and Server 2008. Id need it to be compatible back to XP atleast.


  • Registered Users Posts: 1,994 ✭✭✭lynchie


    Well GetTcpTable() should be compatible from win2k onwards.


  • Advertisement
  • Registered Users Posts: 138 ✭✭MagicRon


    So above, if you couldn't connect to the port, you are returning to say it is available?


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    MagicRon wrote: »
    So above, if you couldn't connect to the port, you are returning to say it is available?

    Yes


  • Registered Users Posts: 4,766 ✭✭✭cython


    Currently im using the below method to determine if a port on my local machine is available for use.

    It seems to work fine but its based on the assumption that the exception thrown is because the port is not in use.

    Is there a better way?

    private bool portAvailable(int port)
    {
    try
    {                
       Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       s.Connect(IPAddress.Loopback, port);
       s.Disconnect(true);
       return false;
    }
    
    catch
    {                
       return true;
    } 
    }
    

    I haven't tested the above, but given that it relies on a failure to connect, I suspect it could be slow (e.g. timeout exception?) to bind initially, though admittedly probably quick to inform about success.

    However, at first glance it seems like leveraging exceptions might be a reasonable solution here. That is to say why don't you try to simply bind to the port, and if successful then stop listening immediately and return true, and return false on the basis of being able to bind? I know that's counter-intuitive if you actually want to listen on the port, but I'm not sure why you've adopted the means that you have, as that in itself is unintuitive....


  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    cython wrote: »
    I haven't tested the above, but given that it relies on a failure to connect, I suspect it could be slow (e.g. timeout exception?) to bind initially, though admittedly probably quick to inform about success.

    However, at first glance it seems like leveraging exceptions might be a reasonable solution here. That is to say why don't you try to simply bind to the port, and if successful then stop listening immediately and return true, and return false on the basis of being able to bind? I know that's counter-intuitive if you actually want to listen on the port, but I'm not sure why you've adopted the means that you have, as that in itself is unintuitive....

    Its really the same regardless of whether i attempt to bind to the port or attempt to connect to the port. Both rely on an exceptions.

    I was hoping there was a nice way of just getting a true/false response on whether the port was in use but that doesnt seem to be the case.

    I might actually change it to attempt to listen as there seems to be a few nice descriptive error codes that get returned when the port is already in use.


  • Registered Users Posts: 4,766 ✭✭✭cython


    Its really the same regardless of whether i attempt to bind to the port or attempt to connect to the port. Both rely on an exceptions.

    I was hoping there was a nice way of just getting a true/false response on whether the port was in use but that doesnt seem to be the case.

    I might actually change it to attempt to listen as there seems to be a few nice descriptive error codes that get returned when the port is already in use.

    Yeah, I realise both mechanisms use exceptions, but I was more referring to using them efficiently, and taking a logical approach - your above approach reads like "Can I do A? If so, then I can't do B. However if I can't do A, then by process of elimination I should be able to achieve B", where you could simply ask "Can I do B? If not, then is it because of X, Y or Z (which exception is generated)?"

    Efficiency revolves around the issue of timeouts associated with connection attempts, as already mentioned.


  • Advertisement
  • Registered Users Posts: 7,501 ✭✭✭BrokenArrows


    cython wrote: »
    Yeah, I realise both mechanisms use exceptions, but I was more referring to using them efficiently, and taking a logical approach - your above approach reads like "Can I do A? If so, then I can't do B. However if I can't do A, then by process of elimination I should be able to achieve B", where you could simply ask "Can I do B? If not, then is it because of X, Y or Z (which exception is generated)?"

    Efficiency revolves around the issue of timeouts associated with connection attempts, as already mentioned.

    I see what you mean.


Advertisement