59 lines
2.1 KiB
C#
59 lines
2.1 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
|
|
namespace Unosquare.Swan {
|
|
/// <summary>
|
|
/// Provides various extension methods for networking-related tasks.
|
|
/// </summary>
|
|
public static class NetworkExtensions {
|
|
/// <summary>
|
|
/// Determines whether the IP address is private.
|
|
/// </summary>
|
|
/// <param name="address">The IP address.</param>
|
|
/// <returns>
|
|
/// True if the IP Address is private; otherwise, false.
|
|
/// </returns>
|
|
/// <exception cref="ArgumentNullException">address.</exception>
|
|
public static Boolean IsPrivateAddress(this IPAddress address) {
|
|
if(address == null) {
|
|
throw new ArgumentNullException(nameof(address));
|
|
}
|
|
|
|
Byte[] octets = address.ToString().Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(Byte.Parse).ToArray();
|
|
Boolean is24Bit = octets[0] == 10;
|
|
Boolean is20Bit = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
|
|
Boolean is16Bit = octets[0] == 192 && octets[1] == 168;
|
|
|
|
return is24Bit || is20Bit || is16Bit;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts an IPv4 Address to its Unsigned, 32-bit integer representation.
|
|
/// </summary>
|
|
/// <param name="address">The address.</param>
|
|
/// <returns>
|
|
/// A 32-bit unsigned integer converted from four bytes at a specified position in a byte array.
|
|
/// </returns>
|
|
/// <exception cref="ArgumentNullException">address.</exception>
|
|
/// <exception cref="ArgumentException">InterNetwork - address.</exception>
|
|
public static UInt32 ToUInt32(this IPAddress address) {
|
|
if(address == null) {
|
|
throw new ArgumentNullException(nameof(address));
|
|
}
|
|
|
|
if(address.AddressFamily != AddressFamily.InterNetwork) {
|
|
throw new ArgumentException($"Address has to be of family '{nameof(AddressFamily.InterNetwork)}'", nameof(address));
|
|
}
|
|
|
|
Byte[] addressBytes = address.GetAddressBytes();
|
|
if(BitConverter.IsLittleEndian) {
|
|
Array.Reverse(addressBytes);
|
|
}
|
|
|
|
return BitConverter.ToUInt32(addressBytes, 0);
|
|
}
|
|
}
|
|
}
|