我想计算广播地址:
IP: 192.168.3.1 Subnet: 255.255.255.0 = 192.168.3.255
在C.
我知道的方式(在反向的IP和子网之间做出花哨的按位OR),但我的问题是我来自MacOSX Cocoa编程的绿色领域.
我查看了ipcal的来源,但无法将其集成到我的代码库中.互联网上必须有一行简单的十行代码,我找不到它.有人能指出我在C中如何做到的简短代码示例吗?
算一算:
broadcast = ip | ( ~ subnet )
(Broadcast = ip-addr或反向子网掩码)
广播地址有一个1
子网掩码有0
位的位.
我理解OP至少对位级算术有一个模糊的理解,但在将字符串转换为数字及其反转时丢失了.这是一个工作(无论如何最小的测试)的例子,使用froh42的计算.
jcomeau@aspire:~/rentacoder/jcomeau/freifunk$ cat inet.c; make inet; ./inet 192.168.3.1 255.255.255.0 #include#include int main(int argc, char **argv) { char *host_ip = argc > 1 ? argv[1] : "127.0.0.1"; char *netmask = argc > 2 ? argv[2] : "255.255.255.255"; struct in_addr host, mask, broadcast; char broadcast_address[INET_ADDRSTRLEN]; if (inet_pton(AF_INET, host_ip, &host) == 1 && inet_pton(AF_INET, netmask, &mask) == 1) broadcast.s_addr = host.s_addr | ~mask.s_addr; else { fprintf(stderr, "Failed converting strings to numbers\n"); return 1; } if (inet_ntop(AF_INET, &broadcast, broadcast_address, INET_ADDRSTRLEN) != NULL) printf("Broadcast address of %s with netmask %s is %s\n", host_ip, netmask, broadcast_address); else { fprintf(stderr, "Failed converting number to string\n"); return 1; } return 0; } cc inet.c -o inet Broadcast address of 192.168.3.1 with netmask 255.255.255.0 is 192.168.3.255