#include<stdio.h>
#define uchar unsigned char
#define uint unsigned int
uchar bin1num(uchar num);
void main() {
uchar IP[] = {192,168,1,53}; //IP地址
uchar SubnetMask[] = {255,255,255,224}; //子网掩码
//网络类型和默认子网掩码缩写
uchar DefaultSubnetMaskAbbr;
if(IP[0]<224) DefaultSubnetMaskAbbr = 24; //C类地址
if(IP[0]<192) DefaultSubnetMaskAbbr = 16; //B类地址
if(IP[0]<128) DefaultSubnetMaskAbbr = 8; //A类地址
//实际子网掩码缩写:二进制中1的个数
uchar SubnetMaskAbbr = bin1num(SubnetMask[0])+bin1num(SubnetMask[1])+bin1num(SubnetMask[2])+bin1num(SubnetMask[3]);
//网络地址:IP & 子网掩码
uchar Network[] = {IP[0] & SubnetMask[0], IP[1] & SubnetMask[1], IP[2] & SubnetMask[2], IP[3] & SubnetMask[3]};
//广播地址:(~子网掩码)|网络地址
uchar Broadcast[] = {(~SubnetMask[0])|Network[0], (~SubnetMask[1])|Network[1], (~SubnetMask[2])|Network[2], (~SubnetMask[3])|Network[3]};
//子网数:2^(实际子网掩码缩写-默认子网掩码缩写)
uint SubnetNum = 1;
for(int i=0; i<SubnetMaskAbbr-DefaultSubnetMaskAbbr; i++) {
SubnetNum *=2;
}
//最大主机数:2^(32-子网掩码缩写)
uint HostNum = 1;
for(int i=0; i<32-SubnetMaskAbbr; i++) {
HostNum *=2;
}
/*打印结果*/
printf("ip地址:%d.%d.%d.%d\n", IP[0], IP[1], IP[2], IP[3]);
printf("子网掩码:%d.%d.%d.%d\n", SubnetMask[0], SubnetMask[1], SubnetMask[2], SubnetMask[3]);
if(DefaultSubnetMaskAbbr==8) printf("网络类型:A类\n");
if(DefaultSubnetMaskAbbr==16) printf("网络类型:B类\n");
if(DefaultSubnetMaskAbbr==24) printf("网络类型:C类\n");
printf("子网掩码缩写:%d\n", SubnetMaskAbbr);
printf("网络地址:%d.%d.%d.%d\n", Network[0], Network[1], Network[2], Network[3]);
printf("广播地址:%d.%d.%d.%d\n", Broadcast[0], Broadcast[1], Broadcast[2], Broadcast[3]);
printf("子网数:%d\n", SubnetNum);
printf("最大主机数:%d\n", HostNum);
printf("可用主机数:%d\n", HostNum-2);
}
//计算8位二进制数1的个数(1必须从第一位开始,每个1必须相邻)
uchar bin1num(uchar num) {
uchar Divisor[] = {128,64,32,16,8,4,2,1}; //除数(8位)
uchar Remainder = num; //余数
uchar ret; //结果
for(ret=0; ret<10; ret++) {
if(Remainder>0) Remainder = Remainder%Divisor[ret];
else break;
}
return ret;
}
|