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

时间:2009-04-22 14:53:07

标签: c ip broadcast subnet

我想计算:

的广播地址
IP:     192.168.3.1
Subnet: 255.255.255.0
=       192.168.3.255

在C。

我知道这种方式(在反向IP和子网之间做出花哨的按位OR),但我的问题是我来自MacOSX Cocoa编程的绿色领域。

我查看了ipcal的来源,但无法将其集成到我的代码库中。互联网上必须有一行简单的十行代码,我找不到它。 有人能指出我在C中如何做到的简短代码示例吗?

5 个答案:

答案 0 :(得分:40)

算一下:

broadcast = ip | ( ~ subnet )

(Broadcast = ip-addr或反向子网掩码)

广播地址有1位,子网掩码的位为0

答案 1 :(得分:5)

我知道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

答案 2 :(得分:3)

可能吗?

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

    return bcast;
}

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

答案 3 :(得分:1)

以下是如何在C#中执行此操作。例如,使用带有网络掩码255.255.252.0的ip 10.28.40.149返回10.28.43.255,这是正确的广播地址。感谢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();
    }

答案 4 :(得分:-1)

好的人将来会查找此代码。我今天有时需要花费,因为我需要这个,这里是完整的代码,它可以工作:)只需复制并粘贴它,然后导入所需的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());

快乐编码:)