如何获得默认网络适配器的主机广播地址?C#

How do you get host's broadcast address of the default network adapter? C#
2021-06-20
  •  译文(汉语)
  •  原文(英语)

假设我想向子网中的每个主机发送udp消息(然后从子网中的任何主机接收udp消息):

目前,我这样做:

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

但是我当然希望在子网不同于192.168.1 / 24的情况下做到这一点.我已经尝试过:

IPAddress broadcast = IPAddress.Broadcast;

但是IPAddress.Broadcast表示"255.255.255.255",它不能用于发送消息(引发异常)...因此:

我如何获取本地网络适配器的广播地址(或网络掩码)?

这是我想出的最终解决方案

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;
}
速聊1:
您发布的解决方案对我来说效果很好.我没有给paqogomez答复,因为您的工作直接粘贴了.想知道您是否应该更改并接受自己的答案?
解决过程1

如果获得本地IP和子网,则计算应该没有问题.

像这样的东西?

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);
            }
        }
    }
}

给定IP地址和网络掩码时,如何计算IP范围?应该给你剩下的.

速聊1:
很好,有了您的回答,我几乎达到了我的目标,最后一个问题:现在,我可以枚举每个接口的所有网络掩码.如何获得本地局域网之一-如果有的话!(计算机可能直接连接到互联网)
速聊2:
查看我的编辑. if (Interface.OperationalStatus != OperationalStatus.Up) continue; 在这之间,以及与NetworkInterface一起使用的其他非常有趣的参数中,您应该拥有它.
速聊3:
我添加了一小段代码,让我得到了正确的遮罩,删除了代码的某些部分(带有continue的部分;指令).基本上,我从Dns对象获取主机的当前IP,然后将其与每个UnicastIPAddressInformationCollection ip进行比较.找到匹配项后,我将返回关联的网络掩码.这似乎有效.当然,我将您作为解决方案,因为您的帮助对于找到解决方案至关重要.

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;
}
Talk1:
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?
Solutions1

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.

Talk1:
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)
Talk2:
Check out my edit. if (Interface.OperationalStatus != OperationalStatus.Up) continue; Between that, and other very interesting parameters with the NetworkInterface You should have it.
Talk3:
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.
转载于:https://stackoverflow.com/questions/18551686/how-do-you-get-hosts-broadcast-address-of-the-default-network-adapter-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入