Skip to content

Instantly share code, notes, and snippets.

@Iman
Last active December 19, 2015 15:29
Show Gist options
  • Save Iman/6d7f7c301a295769b86f to your computer and use it in GitHub Desktop.
Save Iman/6d7f7c301a295769b86f to your computer and use it in GitHub Desktop.
Validate alive IP address in C# (IP health test)
using System;
using System.Net;
using System.Threading;
using System.Net.Sockets;
class test2 {
private static readonly string[] listA = new string[] {"173.194.00.001", "72.233.127.00", "2607:f8b0:4003:c00::6a", "foo"};
private static bool IsIP4;
private static bool isUp;
public static void Main()
{
foreach(string value in listA)
{
System.Console.WriteLine(value);
}
foreach(string value in listA)
{
IfTest(value);
System.Console.WriteLine(IsIP4.ToString());
}
/**
foreach(string value in listA)
{
IsServerUp(value,80,1);
System.Console.WriteLine(isUp);
if (isUp) {
// set h
break;
}
}
*/
IsServerUp("127.0.0.1",80, 10);
System.Console.WriteLine(isUp);
}
public static bool IsServerUp(string server, int port, int timeout)
{
// bool isUp;
try
{
using (TcpClient tcp = new TcpClient())
{
IPAddress address;
if (IPAddress.TryParse(server, out address))
{
IAsyncResult ar = tcp.BeginConnect(address, port, null, null);
WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!wh.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
{
tcp.EndConnect(ar);
tcp.Close();
throw new SocketException();
}
isUp = true;
tcp.EndConnect(ar);
}
finally
{
wh.Close();
}
}
}
}
catch (SocketException)
{
isUp = false;
}
return isUp;
}
private static bool IfTest(string input)
{
IPAddress address;
if (IPAddress.TryParse(input, out address))
{
switch (address.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork:
// we have IPv4i
System.Console.WriteLine("4");
IsIP4 = true;
break;
case System.Net.Sockets.AddressFamily.InterNetworkV6:
// we have IPv6
System.Console.WriteLine("6");
IsIP4 = false;
break;
default:
IsIP4 = false;
break;
}
}
return IsIP4;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment