问题描述
我如何计算 Objective C 中的广播地址
How do I go about calculating the Broadcast Address in Objective C
我希望将广播地址解析为与以下子网计算器相同的结果 - http://www.subnet-calculator.com/subnet.php
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
我有本地 IOS 设备的 IP 地址和子网掩码.而且我知道广播地址使用以下公式
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)
推荐答案
替代方案:
#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)];
这篇关于在 Objective-C 中计算广播地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!