[Go] C # get the native available port

Source: Internet
Author: User

When we are going to create a tcp/udp Server connection, we need a port ranging from 1000 to 65535. However, a port can only be monitored by one program, so we need to detect if the port is occupied when we listen locally. The namespace System.Net.NetworkInformation defines a class named Ipglobalproperties, which we use to get all the listening connections and then determine if the ports are occupied.

1 //----------------------------------------------------------------------------- 2 //Filename:FreePort.cs3 // 4 //Description:helper methods to find the next free UDP and TCP ports.5 // 6 //History :7 //Clauson Aaron Copied fromhttp://www.mattbrindley.com/developing/windows/net/detecting-the-next-available-free-tcp-port/. 8 //-----------------------------------------------------------------------------9 Ten usingSystem; One usingSystem.Collections.Generic; A usingSystem.Linq; - usingSystem.Net; - usingSystem.Net.NetworkInformation; the usingSystem.Text; - usingSystem.Threading; -  - namespaceSIPSorcery.Sys.Net + {  -      Public classFreePort +     {  A         Private Const stringPortreleaseguid ="8875bd8e-4d5b-11de-b2f4-691756d89593"; at  -         /// <summary>  -         ///Check If Startport is available, incrementing and -         ///checking again if it ' s in use until a free port is found -         /// </summary>  -         /// <param name= "Startport" >The first port to check</param>  in         /// <returns>The first available port</returns>  -          Public Static intFindnextavailabletcpport (intstartport) to         {  +             intPort =Startport; -             BOOLIsAvailable =true; the  *             varMutex =NewMutex (false,  $                 string. Concat ("global/", Portreleaseguid)); Panax Notoginseng mutex. WaitOne ();  -             Try  the             {  +Ipglobalproperties ipglobalproperties = A ipglobalproperties.getipglobalproperties (); theipendpoint[] Endpoints = + ipglobalproperties.getactivetcplisteners (); -  $                  Do  $                 {  -                     if(!isavailable) -                     {  theport++;  -IsAvailable =true; Wuyi                     } the  -                     foreach(IPEndPoint EndPointinchendpoints) Wu                     {  -                         if(Endpoint.port! = Port)Continue;  AboutIsAvailable =false;  $                          Break;  -                     } -  -} while(!isavailable && Port <ipendpoint.maxport); A  +                 if(!isavailable) the                     Throw NewApplicationException ("Not able to find a free TCP port."); -  $                 returnPort; the             }  the             finally  the             {  the mutex. ReleaseMutex ();  -             }  in         } the  the         /// <summary>  About         ///Check If Startport is available, incrementing and the         ///checking again if it ' s in use until a free port is found the         /// </summary>  the         /// <param name= "Startport" >The first port to check</param>  +         /// <returns>The first available port</returns>  -          Public Static intFindnextavailableudpport (intstartport) the         { Bayi             intPort =Startport; the             BOOLIsAvailable =true; the  -             varMutex =NewMutex (false,  -                 string. Concat ("global/", Portreleaseguid));  the mutex. WaitOne ();  the             Try  the             {  theIpglobalproperties ipglobalproperties = - ipglobalproperties.getipglobalproperties (); theipendpoint[] Endpoints = the ipglobalproperties.getactiveudplisteners (); the 94                  Do  the                 {  the                     if(!isavailable) the                     { 98port++;  AboutIsAvailable =true;  -                     }101 102                     foreach(IPEndPoint EndPointinchendpoints)103                     { 104                         if(Endpoint.port! =Port) the                             Continue; 106IsAvailable =false; 107                          Break; 108                     }109  the} while(!isavailable && Port <ipendpoint.maxport);111  the                 if(!isavailable)113                     Throw NewApplicationException ("Not able to find a free TCP port."); the  the                 returnPort; the             } 117             finally 118             { 119 mutex. ReleaseMutex ();  -             } 121         } 122     } 123}

[Go] C # get the native available port

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.