根据ip和子网掩码计算广播地址

发布于 2024-07-18 05:37:11 字数 305 浏览 12 评论 0原文

我想计算以下内容的广播地址:

IP:     192.168.3.1
Subnet: 255.255.255.0
=       192.168.3.255

在 C 语言中。

我知道方法(在反转的 IP 和子网之间进行奇特的按位或),但我的问题是我来自 MacOSX Cocoa 编程的绿色领域。

我研究了 ipcal 的源代码,但无法将其集成到我的代码库中。 互联网上一定有一个简单的十行代码,我只是找不到它。 有人能给我提供一个简短的代码示例来说明如何用 C 语言实现这一点吗?

I want to calculate the broadcast address for:

IP:     192.168.3.1
Subnet: 255.255.255.0
=       192.168.3.255

in C.

I know the way (doing fancy bitwise OR's between the inversed IP and subnet), but my problem is I come from the green fields of MacOSX Cocoa programing.

I looked into the source of ipcal, but wasn't able to integrate it into my code base. There must be a simple ten lines of code somewhere on the internet, I just can't find it.
Could someone point me to a short code example of how to do it in C?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

百善笑为先 2024-07-25 05:37:11

只需计算:(

broadcast = ip | ( ~ subnet )

广播 = ip-addr 或反转的子网掩码)

广播地址有一个 1 位,而子网掩码有一个 0 位。

Just calculate:

broadcast = ip | ( ~ subnet )

(Broadcast = ip-addr or the inverted subnet-mask)

The broadcast address has a 1 bit where the subnet mask has a 0 bit.

无人接听 2024-07-25 05:37:11

我知道OP至少对位级算术有一个模糊的理解,但在将字符串转换为数字及其逆时迷失了。 这是一个工作示例(无论如何都进行了最少的测试),使用 froh42 的计算。

jcomeau@aspire:~/rentacoder/jcomeau/freifunk$ cat inet.c; make inet; ./inet 192.168.3.1 255.255.255.0
#include <arpa/inet.h>
#include <stdio.h>
int main(int argc, char **argv) {
    char *host_ip = argc > 1 ? argv[1] : "127.0.0.1";
    char *netmask = argc > 2 ? argv[2] : "255.255.255.255";
    struct in_addr host, mask, broadcast;
    char broadcast_address[INET_ADDRSTRLEN];
    if (inet_pton(AF_INET, host_ip, &host) == 1 &&
        inet_pton(AF_INET, netmask, &mask) == 1)
        broadcast.s_addr = host.s_addr | ~mask.s_addr;
    else {
        fprintf(stderr, "Failed converting strings to numbers\n");
        return 1;
    }
    if (inet_ntop(AF_INET, &broadcast, broadcast_address, INET_ADDRSTRLEN) != NULL)
        printf("Broadcast address of %s with netmask %s is %s\n",
            host_ip, netmask, broadcast_address);
    else {
        fprintf(stderr, "Failed converting number to string\n");
        return 1;
    }
    return 0;
}
cc     inet.c   -o inet
Broadcast address of 192.168.3.1 with netmask 255.255.255.0 is 192.168.3.255

I understand that the OP had at least a vague understanding of the bit-level arithmetic but was lost on converting the strings to numbers and its inverse. here's a working (with minimal testing anyway) example, using froh42's calculation.

jcomeau@aspire:~/rentacoder/jcomeau/freifunk$ cat inet.c; make inet; ./inet 192.168.3.1 255.255.255.0
#include <arpa/inet.h>
#include <stdio.h>
int main(int argc, char **argv) {
    char *host_ip = argc > 1 ? argv[1] : "127.0.0.1";
    char *netmask = argc > 2 ? argv[2] : "255.255.255.255";
    struct in_addr host, mask, broadcast;
    char broadcast_address[INET_ADDRSTRLEN];
    if (inet_pton(AF_INET, host_ip, &host) == 1 &&
        inet_pton(AF_INET, netmask, &mask) == 1)
        broadcast.s_addr = host.s_addr | ~mask.s_addr;
    else {
        fprintf(stderr, "Failed converting strings to numbers\n");
        return 1;
    }
    if (inet_ntop(AF_INET, &broadcast, broadcast_address, INET_ADDRSTRLEN) != NULL)
        printf("Broadcast address of %s with netmask %s is %s\n",
            host_ip, netmask, broadcast_address);
    else {
        fprintf(stderr, "Failed converting number to string\n");
        return 1;
    }
    return 0;
}
cc     inet.c   -o inet
Broadcast address of 192.168.3.1 with netmask 255.255.255.0 is 192.168.3.255
不弃不离 2024-07-25 05:37:11

可能是吗?

unsigned broadcast(unsigned ip,unsigned subnet){
    unsigned int bits = subnet ^ 0xffffffff; 
    unsigned int bcast = ip | bits;

    return bcast;
}

编辑:我认为ip和子网都没有“。”

Could it be?

unsigned broadcast(unsigned ip,unsigned subnet){
    unsigned int bits = subnet ^ 0xffffffff; 
    unsigned int bcast = ip | bits;

    return bcast;
}

Edit: I considered that both ip and subnet are without "."

╭⌒浅淡时光〆 2024-07-25 05:37:11

以下是如何在 C# 中执行此操作。 例如,使用 ip 10.28.40.149 和网络掩码 255.255.252.0 返回 10.28.43.255,这是正确的广播地址。 感谢 此处

private static string GetBroadcastAddress(string ipAddress, string subnetMask) {
        //determines a broadcast address from an ip and subnet
        var ip = IPAddress.Parse(ipAddress);
        var mask = IPAddress.Parse(subnetMask);

        byte[] ipAdressBytes = ip.GetAddressBytes();
        byte[] subnetMaskBytes = mask.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).ToString();
    }

Here is how to do it in C#. for example using ip 10.28.40.149 with netmask 255.255.252.0 returns 10.28.43.255 which is the correct broadcast address. thanks to some code from here

private static string GetBroadcastAddress(string ipAddress, string subnetMask) {
        //determines a broadcast address from an ip and subnet
        var ip = IPAddress.Parse(ipAddress);
        var mask = IPAddress.Parse(subnetMask);

        byte[] ipAdressBytes = ip.GetAddressBytes();
        byte[] subnetMaskBytes = mask.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).ToString();
    }
白昼 2024-07-25 05:37:11

好吧,谁将来会寻找此代码。 我今天有时需要这个,这里是完整的代码,它可以工作:)只需复制并粘贴它,然后导入所需的 dll。

private IPAddress CalculateBroadCastAddress(IPAddress currentIP, IPAddress ipNetMask)
    {
        string[] strCurrentIP = currentIP.ToString().Split('.');
        string[] strIPNetMask = ipNetMask.ToString().Split('.');

        ArrayList arBroadCast = new ArrayList();

        for (int i = 0; i < 4; i++)
        {
            int nrBCOct = int.Parse(strCurrentIP[i]) | (int.Parse(strIPNetMask[i]) ^ 255);
            arBroadCast.Add(nrBCOct.ToString());
        }
        return IPAddress.Parse(arBroadCast[0] + "." + arBroadCast[1] +
               "." + arBroadCast[2] + "." + arBroadCast[3]);
    }


    private IPAddress getIP()
    {
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip;

            }
        }
        return null;
    }

    private IPAddress getSubnetMask()
    {
        NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
        IPAddress ip = getIP();
        foreach (NetworkInterface interf in Interfaces)
        {

            UnicastIPAddressInformationCollection UnicastIPInfoCol = interf.GetIPProperties().UnicastAddresses;

            foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
            {
                if (UnicatIPInfo.Address.Equals(ip))
                    return UnicatIPInfo.IPv4Mask;
            }

        }

        return null;

    }

然后就这样称呼它:

IPAddress  broadcastip = CalculateBroadCastAddress(getIP(), getSubnetMask());

快乐编码:)

ok whom will look for this code in the future. I have spend sometimes today as I needed this, here is the full code and it works :) simply copy and paste it and then import the required dlls.

private IPAddress CalculateBroadCastAddress(IPAddress currentIP, IPAddress ipNetMask)
    {
        string[] strCurrentIP = currentIP.ToString().Split('.');
        string[] strIPNetMask = ipNetMask.ToString().Split('.');

        ArrayList arBroadCast = new ArrayList();

        for (int i = 0; i < 4; i++)
        {
            int nrBCOct = int.Parse(strCurrentIP[i]) | (int.Parse(strIPNetMask[i]) ^ 255);
            arBroadCast.Add(nrBCOct.ToString());
        }
        return IPAddress.Parse(arBroadCast[0] + "." + arBroadCast[1] +
               "." + arBroadCast[2] + "." + arBroadCast[3]);
    }


    private IPAddress getIP()
    {
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip;

            }
        }
        return null;
    }

    private IPAddress getSubnetMask()
    {
        NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces();
        IPAddress ip = getIP();
        foreach (NetworkInterface interf in Interfaces)
        {

            UnicastIPAddressInformationCollection UnicastIPInfoCol = interf.GetIPProperties().UnicastAddresses;

            foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
            {
                if (UnicatIPInfo.Address.Equals(ip))
                    return UnicatIPInfo.IPv4Mask;
            }

        }

        return null;

    }

Then just call it like :

IPAddress  broadcastip = CalculateBroadCastAddress(getIP(), getSubnetMask());

Happy coding :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文