Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created November 27, 2010 21:43
Show Gist options
  • Save beccasaurus/718306 to your computer and use it in GitHub Desktop.
Save beccasaurus/718306 to your computer and use it in GitHub Desktop.
CheckIfPortIsAvailable C#
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