Last active
October 15, 2019 09:31
-
-
Save snerpton/67d0832e118babe73564c8c4dcdf90f6 to your computer and use it in GitHub Desktop.
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
//Not my code, but not sure where it came from. | |
using System; | |
using System.Net; | |
public static class IPAddressExtensions | |
{ | |
public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask) | |
{ | |
byte[] ipAdressBytes = address.GetAddressBytes(); | |
byte[] subnetMaskBytes = subnetMask.GetAddressBytes(); | |
if (ipAdressBytes.Length != subnetMaskBytes.Length) | |
throw new ArgumentException("Lengths of IP address and subnet mask do not match."); | |
byte[] broadcastAddress = new byte[ipAdressBytes.Length]; | |
for (int i = 0; i < broadcastAddress.Length; i++) | |
{ | |
broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255)); | |
} | |
return new IPAddress(broadcastAddress); | |
} | |
public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask) | |
{ | |
byte[] ipAdressBytes = address.GetAddressBytes(); | |
byte[] subnetMaskBytes = subnetMask.GetAddressBytes(); | |
if (ipAdressBytes.Length != subnetMaskBytes.Length) | |
throw new ArgumentException("Lengths of IP address and subnet mask do not match."); | |
byte[] broadcastAddress = new byte[ipAdressBytes.Length]; | |
for (int i = 0; i < broadcastAddress.Length; i++) | |
{ | |
broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i])); | |
} | |
return new IPAddress(broadcastAddress); | |
} | |
public static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask) | |
{ | |
IPAddress network1 = address.GetNetworkAddress(subnetMask); | |
IPAddress network2 = address2.GetNetworkAddress(subnetMask); | |
return network1.Equals(network2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment