Baidu a bit, the main two ways:
1. Using the getactivetcplisteners () method
How to use Baidu a lot of articles, but I tried after, get the port list with Netstat-ano A comparison, completely wrong, as to why, did not find the relevant article, see the data for a long time also did not find what reason, to this more familiar friends can be pointing under what reason.
2, using the process run netstat –ano command, get to the output text, get the port information that has been occupied.
This method has a very hole in the place, most of the article's practice is:
list<int> ports = new List<int> ();
process Pro = new process();
Pro. Startinfo.filename = "cmd.exe";
Pro. Startinfo.useshellexecute = false;
Pro. Startinfo.redirectstandardinput = true;
Pro. Startinfo.redirectstandardoutput = true;
Pro. Startinfo.redirectstandarderror = true;
Pro. Startinfo.createnowindow = true;
Pro. Start ();
Pro. Standardinput.writeline ("Netstat-ano");
Pro. Standardinput.writeline ("exit");
regex reg = new regex("\\s+");
string Line = null;
Ports. Clear ();
while (line = Pro. Standardoutput.readline ()) = null)
{
}
After I tried, and did not get the relevant content, only to the following lines of text:
Microsoft Windows [version 10.0.16299.309]
(c) Microsoft Corporation. All rights reserved.
C:\users\suyu>netstat–ano
C:\users\suyu>exit
After a day of trying, I finally find the right way to open it when it's going to crash:
/// <summary> ///returns the available port number/// </summary> /// <returns></returns> Public intGetavailableport () {intBeginport =50000;//Start Port intEndport =65535;//End PortProcess P=NewProcess (); P.startinfo=NewProcessStartInfo ("netstat","-an"); P.startinfo.createnowindow=true; P.startinfo.useshellexecute=false; P.startinfo.windowstyle=Processwindowstyle.hidden; P.startinfo.redirectstandardoutput=true; P.start (); List<int> ports =Newlist<int>(); stringline =NULL; Regex Reg=NewRegex ("\\s+"); while(line = P.standardoutput.readline ())! =NULL) { line=Line . Trim (); if(line. StartsWith ("TCP", stringcomparison.ordinalignorecase) | |Line . StartsWith ("UDP", StringComparison.OrdinalIgnoreCase)) { Line= Reg. Replace (Line,","); string[] arr = line. Split (','); stringSoc = arr[1]; intpos = Soc. LastIndexOf (':'); intPort =int. Parse (Soc. Substring (pos +1)); //greater than the beginning eloquence record if(Port >=beginport) ports. ADD (port); }} p.close (); intresult =Beginport; for(inti = Beginport; i < Endport; i++) { if(Ports. FindIndex (A = a = = i) >-1) Continue; Else{result=i; Break; } } returnresult; }
Get a port number in unity that is not used by this machine