在Objective-C中计算广播地址

时间:2021-03-18 22:32:45

How do I go about calculating the Broadcast Address in Objective C

如何计算Objective C中的广播地址

I would like to have the Broadcast Address resolve to the same result as shown in the following Subnet Calculator - http://www.subnet-calculator.com/subnet.php

我希望广播地址解析与以下子网计算器(http://www.subnet-calculator.com/subnet.php)显示的结果相同

I have the IP Address of my local IOS device and the Subnet Mask. And I know that the Broadcast Address uses the following formula

我有本地IOS设备的IP地址和子网掩码。我知道广播地址使用以下公式

broadcast = ip | ( ~ subnet )

(I am answering my self, as I have not seen this on the Internet anywhere, and also I am not aware of any libraries which perform this calculation. Happy to see if anyone else has a better solution or is aware of any libraries)

(我在回答我自己的问题,因为我在任何地方都没有见过这种情况,而且我也不知道有哪个图书馆执行这个计算。)很高兴看到其他人是否有更好的解决方案或知道任何库)

3 个解决方案

#1


5  

Alternative solution:

可选择的解决方案:

#include <net/ethernet.h>
#include <arpa/inet.h>

NSString *localIPAddress = @"192.168.1.10";
NSString *netmaskAddress = @"255.255.192.0";

// Strings to in_addr:
struct in_addr localAddr;
struct in_addr netmaskAddr;
inet_aton([localIPAddress UTF8String], &localAddr);
inet_aton([netmaskAddress UTF8String], &netmaskAddr);

// The broadcast address calculation:
localAddr.s_addr |= ~(netmaskAddr.s_addr);

// in_addr to string:
NSString *broadCastAddress = [NSString stringWithUTF8String:inet_ntoa(localAddr)];

#2


3  

You don't need to provide IP address & subnet-mask to calculate "Broadcast" address of any network interface. Actually you don't need to manually calculate it.

您不需要提供IP地址和子网掩码来计算任何网络接口的“广播”地址。实际上,您不需要手动计算它。

There is ifaddrs Structure that describes a network host. It provides complete details of any network interface. By using getifaddrs() method, you can retrieve Broadcast address of the network without providing IP & subnet mask as attribute. Function itself retrieves the details. I'd prefer this because this will make code more generic.

有一个描述网络主机的ifaddrs结构。它提供任何网络接口的完整细节。通过使用getifaddrs()方法,您可以检索网络的广播地址,而无需提供IP和子网掩码作为属性。函数本身检索细节。我更喜欢这样,因为这会使代码更通用。

I am using this in my code.

我在代码中使用这个。

#import <ifaddrs.h> // for interface addresses needed to find local IP

static NSString * broadcastAddress()
//Gets Local IP of the device over Wifi
//Calculates & returns broadcast Address for the network
{
    NSString * broadcastAddr= @"Error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);

    if (success == 0)
    {
        temp_addr = interfaces;

        while(temp_addr != NULL)
        {
            // check if interface is en0 which is the wifi connection on the iPhone
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    broadcastAddr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];

                }
            }

            temp_addr = temp_addr->ifa_next;
        }
    }

    freeifaddrs(interfaces);
    return broadcastAddr;
}

To know more about ifaddrs structure See this

要了解ifaddrs结构的更多信息,请参见本文

#3


0  

The following code can be used to calculate the broadcast address, all you need is the IP Address and the Subnet Mask in a NSString type to perform the calculation.

下面的代码可以用来计算广播地址,您只需要IP地址和NSString类型中的子网掩码来执行计算。

////////////////////////////////////////////////////////
// Calculates the local broadcast packet from Local IP Address and Subnet Mask.
// Uses the following calculation:-
// broadcast = ip | ( ~ subnet )   i.e. Broadcast = ip-addr OR the inverted subnet-mask
////////////////////////////////////////////////////////

// Local IP Address and Subnet Mask
NSString *localIPAddress = @"192.168.1.10";
NSString *netmaskAddress = @"255.255.192.0";

// Separate out the subnet mask values and assign them to variables as integers
NSScanner* scannerNetmask = [NSScanner scannerWithString:netmaskAddress];
[scannerNetmask setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int aNetmask, bNetmask, cNetmask, dNetmask;
[scannerNetmask scanInt:&aNetmask];
[scannerNetmask scanInt:&bNetmask];
[scannerNetmask scanInt:&cNetmask];
[scannerNetmask scanInt:&dNetmask];

// Separate out the ip address values and assign them to variables as integers
NSScanner* scannerLocalIP = [NSScanner scannerWithString:localIPAddress];
[scannerLocalIP setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int aLocalIP, bLocalIP, cLocalIP, dLocalIP;
[scannerLocalIP scanInt:&aLocalIP];
[scannerLocalIP scanInt:&bLocalIP];
[scannerLocalIP scanInt:&cLocalIP];
[scannerLocalIP scanInt:&dLocalIP];

// Calculate the bitwise inversion of the Netmask
// Do this by first casting value as a unsigned char (1 byte, no complement)
unsigned char biNetmask, ciNetmask, diNetmask;
biNetmask = ~(unsigned char)bNetmask;
ciNetmask = ~(unsigned char)cNetmask;
diNetmask = ~(unsigned char)dNetmask;

// Calculating the separated values for the broadcast address
unsigned char bBroadcast, cBroadcast, dBroadcast;
bBroadcast = (unsigned char)bLocalIP | biNetmask;
cBroadcast = (unsigned char)cLocalIP | ciNetmask;
dBroadcast = (unsigned char)dLocalIP | diNetmask;

// Create the Broadcast Address from separate values and display in the console
NSString broadcastAddress = [NSString stringWithFormat:@"%d.%d.%d.%d", aLocalIP, bBroadcast, cBroadcast, dBroadcast];
 NSLog(@"Broadcast Address: %@", broadcastAddress);

#1


5  

Alternative solution:

可选择的解决方案:

#include <net/ethernet.h>
#include <arpa/inet.h>

NSString *localIPAddress = @"192.168.1.10";
NSString *netmaskAddress = @"255.255.192.0";

// Strings to in_addr:
struct in_addr localAddr;
struct in_addr netmaskAddr;
inet_aton([localIPAddress UTF8String], &localAddr);
inet_aton([netmaskAddress UTF8String], &netmaskAddr);

// The broadcast address calculation:
localAddr.s_addr |= ~(netmaskAddr.s_addr);

// in_addr to string:
NSString *broadCastAddress = [NSString stringWithUTF8String:inet_ntoa(localAddr)];

#2


3  

You don't need to provide IP address & subnet-mask to calculate "Broadcast" address of any network interface. Actually you don't need to manually calculate it.

您不需要提供IP地址和子网掩码来计算任何网络接口的“广播”地址。实际上,您不需要手动计算它。

There is ifaddrs Structure that describes a network host. It provides complete details of any network interface. By using getifaddrs() method, you can retrieve Broadcast address of the network without providing IP & subnet mask as attribute. Function itself retrieves the details. I'd prefer this because this will make code more generic.

有一个描述网络主机的ifaddrs结构。它提供任何网络接口的完整细节。通过使用getifaddrs()方法,您可以检索网络的广播地址,而无需提供IP和子网掩码作为属性。函数本身检索细节。我更喜欢这样,因为这会使代码更通用。

I am using this in my code.

我在代码中使用这个。

#import <ifaddrs.h> // for interface addresses needed to find local IP

static NSString * broadcastAddress()
//Gets Local IP of the device over Wifi
//Calculates & returns broadcast Address for the network
{
    NSString * broadcastAddr= @"Error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;

    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);

    if (success == 0)
    {
        temp_addr = interfaces;

        while(temp_addr != NULL)
        {
            // check if interface is en0 which is the wifi connection on the iPhone
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {
                    broadcastAddr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];

                }
            }

            temp_addr = temp_addr->ifa_next;
        }
    }

    freeifaddrs(interfaces);
    return broadcastAddr;
}

To know more about ifaddrs structure See this

要了解ifaddrs结构的更多信息,请参见本文

#3


0  

The following code can be used to calculate the broadcast address, all you need is the IP Address and the Subnet Mask in a NSString type to perform the calculation.

下面的代码可以用来计算广播地址,您只需要IP地址和NSString类型中的子网掩码来执行计算。

////////////////////////////////////////////////////////
// Calculates the local broadcast packet from Local IP Address and Subnet Mask.
// Uses the following calculation:-
// broadcast = ip | ( ~ subnet )   i.e. Broadcast = ip-addr OR the inverted subnet-mask
////////////////////////////////////////////////////////

// Local IP Address and Subnet Mask
NSString *localIPAddress = @"192.168.1.10";
NSString *netmaskAddress = @"255.255.192.0";

// Separate out the subnet mask values and assign them to variables as integers
NSScanner* scannerNetmask = [NSScanner scannerWithString:netmaskAddress];
[scannerNetmask setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int aNetmask, bNetmask, cNetmask, dNetmask;
[scannerNetmask scanInt:&aNetmask];
[scannerNetmask scanInt:&bNetmask];
[scannerNetmask scanInt:&cNetmask];
[scannerNetmask scanInt:&dNetmask];

// Separate out the ip address values and assign them to variables as integers
NSScanner* scannerLocalIP = [NSScanner scannerWithString:localIPAddress];
[scannerLocalIP setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int aLocalIP, bLocalIP, cLocalIP, dLocalIP;
[scannerLocalIP scanInt:&aLocalIP];
[scannerLocalIP scanInt:&bLocalIP];
[scannerLocalIP scanInt:&cLocalIP];
[scannerLocalIP scanInt:&dLocalIP];

// Calculate the bitwise inversion of the Netmask
// Do this by first casting value as a unsigned char (1 byte, no complement)
unsigned char biNetmask, ciNetmask, diNetmask;
biNetmask = ~(unsigned char)bNetmask;
ciNetmask = ~(unsigned char)cNetmask;
diNetmask = ~(unsigned char)dNetmask;

// Calculating the separated values for the broadcast address
unsigned char bBroadcast, cBroadcast, dBroadcast;
bBroadcast = (unsigned char)bLocalIP | biNetmask;
cBroadcast = (unsigned char)cLocalIP | ciNetmask;
dBroadcast = (unsigned char)dLocalIP | diNetmask;

// Create the Broadcast Address from separate values and display in the console
NSString broadcastAddress = [NSString stringWithFormat:@"%d.%d.%d.%d", aLocalIP, bBroadcast, cBroadcast, dBroadcast];
 NSLog(@"Broadcast Address: %@", broadcastAddress);