How do I go about calculating the Broadcast Address in 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
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
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)
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)];
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With