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 Su
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.
////////////////////////////////////////////////////////
// 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);