修改下列代码增加可以按需分配构造超网功能:import javaio; public class ffdg param args public static void mainString argsthrows IOException TODO Auto-generated method stub String ip; 用于接收要划分的IP int s;
import java.io.*;
public class ffdg {
/**
* @param args
*/
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
String ip; //用于接收要划分的IP
int s; //用于接收以要划分的子网数
int n; //输入子网数对应的二进制位数
System.out.println("---------------划分子网---------------");
//输入要划分的IP地址:ip
System.out.println("请输入要划分的IP地址(格式为:x1.x2.x3.x4):");
System.out.print("→:");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
ip = br.readLine();
//截取x1
int index1 = ip.indexOf('.');
String st1 = ip.substring(0,index1);
int x1=Integer.parseInt(st1);//把String类型的st转化成int型
//截取x2
int index2= ip.indexOf('.',index1+1);
String st2 = ip.substring(index1+1,index2);
int x2=Integer.parseInt(st2);//把String类型的st转化成int型
//截取x3
int index3= ip.indexOf('.',index2+1);
String st3 = ip.substring(index2+1,index3);
int x3=Integer.parseInt(st3);//把String类型的st转化成int型
//截取x4
//A类
if(x1>0&&x1<=126){
System.out.println("本IP地址能划分划分的最大子网数为: "+((int)Math.pow(2,24-2)-2));
}
//B类
if(x1>=128&&x1<=191){
System.out.println("本IP地址能划分划分的最大子网数为: "+((int)Math.pow(2,16-2)-2));
}
//C类
if(x1>=192&&x1<=223){
System.out.println("本IP地址能划分划分的最大子网数为: "+((int)Math.pow(2,8-2)-2));
}
//输入要划分的子网数数:s
System.out.println("请输入要划分的子网数:");
System.out.print("→:");
String subnet_num= br.readLine();
s = Integer.parseInt(subnet_num);
br.close();
//求所输入子网数对应的二进制位数:n
int maxSubnets = 0;
int subnetMask = 0;
int maxHosts = 0;
for(n=1; n<=30; n++) {
int subnets = (int)Math.pow(2, n);
int hosts = (int)Math.pow(2, 32-n)-2;
if(subnets >= s && maxSubnets < subnets) {
maxSubnets = subnets;
subnetMask = 0xffffffff << (32-n);
maxHosts = hosts;
}
}
System.out.println("--------------------------------------");
//求子网掩码
System.out.println("子网掩码为:");
System.out.println(((subnetMask >> 24) & 0xff) + "." + ((subnetMask >> 16) & 0xff) + "." + ((subnetMask >> 8) & 0xff) + "." + (subnetMask & 0xff));
System.out.println("每网段主机数:");
System.out.println(maxHosts);
//输出各子网IP范围
System.out.println("各子网IP范围如下:");
for(int i=0; i<maxSubnets; i++) {
int subnetId = i << (32-n);
System.out.print("<"+(i+1)+">"+" ");
System.out.println(((subnetId >> 24) & 0xff) + "." + ((subnetId >> 16) & 0xff) + "." + ((subnetId >> 8) & 0xff) + "." + ((subnetId & 0xff)+1) + "---" + ((subnetId >> 24) & 0xff) + "." + ((subnetId >> 16) & 0xff) + "." + ((subnetId >> 8) & 0xff) + "." + ((subnetId & 0xff)+(int)Math.pow(2,32-n)-2));
}
System.out.println("子网划分完毕");
}
原文地址: http://www.cveoy.top/t/topic/flVx 著作权归作者所有。请勿转载和采集!