8

Let's say that I want to send an udp message to every host in my subnet (and then receive an udp message from any host in my subnet):

at the moment I do:

IPAddress broadcast = IPAddress.Parse("192.168.1.255");

but of course I want this to be done dinamically in the event that the subnet is different from 192.168.1/24. I've tried with:

IPAddress broadcast = IPAddress.Broadcast;

but IPAddress.Broadcast represents "255.255.255.255" which can't be used to send messages (it throws an exception)...so:

how do I get the local network adapter broadcast address (or netmask of course)?

THIS IS THE FINAL SOLUTION I CAME UP WITH

public IPAddress getBroadcastIP()
{
    IPAddress maskIP = getHostMask();
    IPAddress hostIP = getHostIP();

    if (maskIP==null || hostIP == null)
        return null;

    byte[] complementedMaskBytes = new byte[4];
    byte[] broadcastIPBytes = new byte[4];

    for (int i = 0; i < 4; i++)
    {
        complementedMaskBytes[i] =  (byte) ~ (maskIP.GetAddressBytes().ElementAt(i));
        broadcastIPBytes[i] = (byte) ((hostIP.GetAddressBytes().ElementAt(i))|complementedMaskBytes[i]);
    }

    return new IPAddress(broadcastIPBytes);

}


private IPAddress getHostMask()
{

    NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();

    foreach (NetworkInterface Interface in Interfaces)
    {

        IPAddress hostIP = getHostIP();

        UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;

        foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
        {
            if (UnicatIPInfo.Address.ToString() == hostIP.ToString())
            {
                return UnicatIPInfo.IPv4Mask;
            }
        }
    }

    return null;
}

private IPAddress getHostIP()
{
    foreach (IPAddress ip in (Dns.GetHostEntry(Dns.GetHostName())).AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
            return ip;
    }

    return null;
}
Carlo Arnaboldi
  • 363
  • 2
  • 15
  • 1
    Your posted solution worked well for me. I didn't give paqogomez answer a go because yours worked direct paste. Wondering if you should change and accept your own answer? – ScottN Oct 02 '14 at 14:09

1 Answers1

6

If you get the local IP and subnet, it should be no problem to calculate.

Something like this maybe?

using System;
using System.Net.NetworkInformation;

public class test
{
    public static void Main()
    {
        NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach(NetworkInterface Interface in Interfaces)
        {
            if(Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
            if (Interface.OperationalStatus != OperationalStatus.Up) continue;
            Console.WriteLine(Interface.Description);
            UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses;
            foreach(UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
            {
                Console.WriteLine("\tIP Address is {0}", UnicatIPInfo.Address);
                Console.WriteLine("\tSubnet Mask is {0}", UnicatIPInfo.IPv4Mask);
            }
        }
    }
}

How to calculate the IP range when the IP address and the netmask is given? Should give you the rest of it.

Community
  • 1
  • 1
crthompson
  • 15,653
  • 6
  • 58
  • 80
  • Very well, with your answer I've almost reached my goal, one last question: now I can enumerate all network masks of every interface. How to get the one of the local LAN network - if there's any! (the computer may be directly connected to the internet) – Carlo Arnaboldi Aug 31 '13 at 19:31
  • Check out my edit. `if (Interface.OperationalStatus != OperationalStatus.Up) continue;` Between that, and other very interesting parameters with the [NetworkInterface](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.aspx) You should have it. – crthompson Aug 31 '13 at 19:48
  • 1
    I added a small piece of code which let me get the right mask, removing some parts of your code (the ones with continue; instruction). Basically I get the host current IP from the Dns object and then I compare it with each UnicastIPAddressInformationCollection ip's. When I find a match, I return the associated network mask. This seems to work. Of course I put yours as the solution since your help was fundamental in finding a solution. – Carlo Arnaboldi Aug 31 '13 at 21:57