File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -91,7 +91,7 @@ public override ICommandLineParserResult ParseArgs(string[] args)
9191 Parser
9292 . Setup < int > ( 'p' , "port" )
9393 . WithDescription ( $ "Local port to listen on. Default: { DefaultPort } ")
94- . SetDefault ( hostSettings . LocalHttpPort == default ( int ) ? DefaultPort : hostSettings . LocalHttpPort )
94+ . SetDefault ( hostSettings . LocalHttpPort == default ( int ) ? NetworkHelpers . GetNextAvailablePort ( DefaultPort ) : hostSettings . LocalHttpPort )
9595 . Callback ( p => Port = p ) ;
9696
9797 Parser
Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Linq ;
14using System . Net ;
5+ using System . Net . NetworkInformation ;
26using System . Net . Sockets ;
37
48namespace Azure . Functions . Cli . Helpers
@@ -33,5 +37,33 @@ public static int GetAvailablePort()
3337 listener . Stop ( ) ;
3438 }
3539 }
40+
41+ public static int GetNextAvailablePort ( int startPort )
42+ {
43+ var usedPorts = new List < int > ( ) ;
44+ var ipGlobalProperties = IPGlobalProperties . GetIPGlobalProperties ( ) ;
45+
46+ usedPorts . AddRange ( ipGlobalProperties
47+ . GetActiveTcpConnections ( )
48+ . Where ( c => c . LocalEndPoint . Port >= startPort )
49+ . Select ( c => c . LocalEndPoint . Port ) ) ;
50+ usedPorts . AddRange ( ipGlobalProperties
51+ . GetActiveTcpListeners ( )
52+ . Where ( l => l . Port >= startPort )
53+ . Select ( l => l . Port ) ) ;
54+
55+ usedPorts . Sort ( ) ;
56+
57+ foreach ( var usedPort in usedPorts )
58+ {
59+ if ( startPort < usedPort )
60+ {
61+ return startPort ;
62+ }
63+ startPort ++ ;
64+ }
65+
66+ return GetAvailablePort ( ) ;
67+ }
3668 }
3769}
You can’t perform that action at this time.
0 commit comments