Created
November 27, 2010 21:43
-
-
Save beccasaurus/718306 to your computer and use it in GitHub Desktop.
CheckIfPortIsAvailable C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
public class CheckIfPortIsAvailable { | |
public static bool IsAvailable(int portNumber) { | |
var localhost = (IPAddress) Dns.GetHostAddresses("localhost")[0]; | |
try { | |
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
sock.Connect(localhost, portNumber); | |
if (sock.Connected == true) // Port is in use and connection is successful | |
return false; | |
else | |
throw new Exception("Not connected to port ... but no Exception was thrown?"); | |
} catch (SocketException ex) { | |
if (ex.ErrorCode == 10061) // Port is unused and could not establish connection | |
return true; | |
else | |
throw ex; | |
} | |
} | |
public static void Main(string[] args) { | |
var port = int.Parse(args[0]); | |
var available = IsAvailable(port); | |
if (available) | |
Console.WriteLine("Port {0} is available", port); | |
else | |
Console.WriteLine("Port {0} is NOT available", port); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment