Skip to content

Instantly share code, notes, and snippets.

@nikanos
Last active February 18, 2020 23:33
Show Gist options
  • Save nikanos/88d78ae53dc35f206de3aa476886516c to your computer and use it in GitHub Desktop.
Save nikanos/88d78ae53dc35f206de3aa476886516c to your computer and use it in GitHub Desktop.
IsInternal IPAddress Extension
using System;
using System.Net;
using System.Net.Sockets;
static class IPAddressExtensions
{
public static bool IsInternal(this IPAddress address)
{
if (address == null)
throw new ArgumentNullException(nameof(address));
if (address.AddressFamily != AddressFamily.InterNetwork && address.AddressFamily != AddressFamily.InterNetworkV6)
throw new ArgumentException("Only IPv4 & IPv6 addresses are supported", nameof(address));
if (IPAddress.IsLoopback(address))
return true;
if (address.AddressFamily == AddressFamily.InterNetwork)
{
// Private IPv4 Addresses
// 10.0.0.0 - 10.255.255.255
// 172.16.0.0 - 172.31.255.255
// 192.168.0.0 - 192.168.255.255
byte[] addressBytes = address.GetAddressBytes();
switch (addressBytes[0])
{
case 10:
return true;
case 172:
return addressBytes[1] >= 16 && addressBytes[1] < 32;
case 192:
return addressBytes[1] == 168;
default:
return false;
}
}
else if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
// Unique Local IPv6 Unicast Addresses - See https://www.rfc-editor.org/rfc/rfc4193.txt
// fc00::/7
byte[] addressBytes = address.GetAddressBytes();
return addressBytes[0] == 0xFC || addressBytes[0] == 0xFD;
}
return false;
}
}
using System;
using System.Net;
class Program
{
static void Main()
{
PrintIsInternal("127.0.0.1"); //True
PrintIsInternal("10.0.0.1"); //True
PrintIsInternal("172.16.0.1"); //True
PrintIsInternal("192.168.0.1"); //True
PrintIsInternal("fd04:5824:642e:2c13::"); //True
//result of nslookup for www.google.com: 2a00:1450:4006:805::2004
PrintIsInternal("2a00:1450:4006:805::2004"); //False
PrintIsInternal("1.2.3.4"); //False
}
static void PrintIsInternal(string ip)
{
Console.WriteLine($"IsInternal for {ip} returns {IPAddress.Parse(ip).IsInternal()}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment