Calculating the Broadcast Address in Objective-C

Calculating the Broadcast Address in Objective-C

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)];

How do I get the broadcast address of my wifi network using Swift?

Your broadcast address depends on your host address and the subnet mask. You can find the formula to calculate the broadcast address on Wikipedia:

broadcastAddress = ipAddress | ~subnetMask

You can calculate it with the following function:

func calculateBroadcastAddress(ipAddress: String, subnetMask: String) -> String {
let ipAdressArray = ipAddress.split(separator: ".")
let subnetMaskArray = subnetMask.split(separator: ".")
guard ipAdressArray.count == 4 && subnetMaskArray.count == 4 else {
return "255.255.255.255"
}
var broadcastAddressArray = [String]()
for i in 0..<4 {
let ipAddressByte = UInt8(ipAdressArray[i]) ?? 0
let subnetMaskbyte = UInt8(subnetMaskArray[i]) ?? 0
let broadcastAddressByte = ipAddressByte | ~subnetMaskbyte
broadcastAddressArray.append(String(broadcastAddressByte))
}
return broadcastAddressArray.joined(separator: ".")
}

Example:

let broadcastAddress = calculateBroadcastAddress(ipAddress: "172.16.0.0", subnetMask: "255.240.0.0")

Result:

"172.31.255.255"

In general, you should never choose the main queue for network operations because it will lead to lags in the user interface (which is drawn in the main queue). Better use

let udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.global())

Do not forget to explicitly enable broadcasts for this socket

do {
try udpSocket?.enableBroadcast(true)
} catch let error {
print(error)
}

Also consider that Apple enforces an iOS app to work with IPv6, which does not support broadcasts but multicasts. So maybe you should switch to multicasts at least if your device is inside a pure IPv6 network.

Objective C String Manipulation of an IP Address

NSScanner* scanner = [NSScanner scannerWithString:idAddress];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int a, b, c;
[scanner scanInt:&a];
[scanner scanInt:&b];
[scanner scanInt:&c];
NSString* result = [NSString stringWithFormat:@"%d.%d.%d.255", a, b, c];


Related Topics



Leave a reply



Submit