Hi, I have a scenario wherein I need to give access of a system to the hosts of a subnet. For that I need to verify if the incoming request is from the IP which falls within the subnet. Is there some way to do that automatically using c# functionality.

Dani AI

Generated

— quick, practical clarification that builds on and .

An IP address by itself does not contain subnet information (as said). The reliable check is a bitwise comparison: compute the network portion with (IP & Mask) and compare it to the subnet's network base masked the same way. That determines membership. To also enforce “host” addresses (not the network or broadcast), compute the broadcast as (NetworkBase | ~Mask) and exclude both network base and broadcast.

The algorithm in plain steps:

  1. Parse IP, network base and mask to IPAddress and ensure the same AddressFamily.
  2. Use GetAddressBytes() for all three.
  3. For each byte, verify (ipByte & maskByte) == (networkByte & maskByte).
  4. If excluding network/broadcast, compute network base and broadcast and reject those exact addresses.

Example C# implementation:

using System.Net;
using System.Linq;

public static bool IsInSubnet(IPAddress address, IPAddress network, IPAddress mask, bool excludeNetworkAndBroadcast = false)
{
    var a = address.GetAddressBytes();
    var n = network.GetAddressBytes();
    var m = mask.GetAddressBytes();
    if (a.Length != m.Length || n.Length != m.Length) return false;
    for (int i = 0; i < a.Length; i++)
        if ((a[i] & m[i]) != (n[i] & m[i])) return false;
    if (!excludeNetworkAndBroadcast) return true;
    var netBase = new byte[a.Length];
    var bcast = new byte[a.Length];
    for (int i = 0; i < a.Length; i++)
    {
        netBase[i] = (byte)(n[i] & m[i]);
        bcast[i] = (byte)(netBase[i] | (byte)~m[i]);
    }
    return !(a.SequenceEqual(netBase) || a.SequenceEqual(bcast));
}

Practical notes: for 255.255.255.224 (/27) networks the blocks step by 32: .0, .32, .64, etc. The address 192.168.10.32 is the network base for the 32–63 block (so not a usable host); 192.168.10.33 is a host. Use GetAddressBytes to avoid endianness pitfalls; validate mask shape (contiguous ones) when masks are supplied by users; handle IPv6 by applying the same bytewise logic with a prefix-based mask.

Recommended Answers

All 3 Replies

subnet info is not embedded to ip address, it is not in that context.
subnet mask can be anything for a given ip address. subnet masks are used to group ip addresses. what you can know about ip address could only be its type like a,b or c.

It is like with given subnet , its not possible to have a host with IP 192.168.10.32.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.