java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java IP地址计算

java IP地址网段计算的示例代码

作者:记录代码生活

这篇文章主要介绍了java IP地址网段计算的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

根据IP地址与字段掩码计算网段最大最小IP

package c04;
import java.net.UnknownHostException;


public class IPNetworkSegmentCalculation {
  public static void main(String[] args) throws UnknownHostException {
    String ip = "192.168.126.2";
    String mask = "255.255.255.0";
    findMask();
  }
  public static void findMask(){
    String mask = "255.255.255.0";
    String ip = "192.168.126.2";
    String[] ipArray =  ip.split("[.]");
    String[] maskArray = mask.split("[.]");

    String minIp = "";
    String maxIp = "";
    int subMask = 0;
    for(int i=0 ;i < maskArray.length ; i++){
      int maskTmp = Integer.valueOf(maskArray[i]);
      int ipTmp = Integer.valueOf(ipArray[i]);
      int mi = maskTmp&ipTmp;

      //System.out.println("==============="+maskTmp+" "+ipTmp);
      if(ipTmp == mi && maskTmp==255){
        minIp = minIp + ipTmp+"." ;
        maxIp = maxIp + ipTmp+"." ;
        subMask = subMask + 8;
      }else{
        minIp = minIp + mi+"." ;
        maxIp = maxIp + maxNetSeg(Integer.toBinaryString(maskTmp),mi)+".";
        subMask = subMask + subMaskNum(Integer.toBinaryString(maskTmp));
      }


    }

    minIp = minIp.substring(0,minIp.length()-1);
    maxIp = maxIp.substring(0,maxIp.length()-1);
    System.out.println("minip "+minIp);
    System.out.println("maxip "+maxIp);
    System.out.println("mask "+subMask);
  }
  private static int calculate(int n) {
    if (n == 0)
      return 1;
    return 2 * calculate(n - 1);
  }

  private static Integer maxNetSeg(String s1,int mi){
    s1 = new StringBuffer(s1).reverse().toString();

    if(s1.indexOf("1")!=-1){
      int i = s1.indexOf("1");
      return mi+calculate(i);
    }else {
      return 255;
    }

  }
  private static Integer subMaskNum(String s1){
    if(s1.lastIndexOf("1")!=-1){
      int i = s1.lastIndexOf("1") + 1;
      return i;
    }
    return 0;

  }
}

Java根据网段计算子网掩码,起始IP,结束IP

/**
 * IP的相关计算
 * @author zengchaowang
 * @version 1.0
 *
 */
public class IpCaculate {
 
	/**
	 * 根据掩码位数计算掩码
	 * @param maskIndex 掩码位
	 * @return 子网掩码
	 */
	public static String getNetMask(String maskIndex) {
		StringBuilder mask = new StringBuilder();
		Integer inetMask = 0;
		try {
			inetMask = Integer.parseInt(maskIndex);
		} catch (NumberFormatException e) {
			System.out.println(e.getMessage());
			return null;
		}
		if (inetMask > 32) {
			return null;
		}
		// 子网掩码为1占了几个字节
		int num1 = inetMask / 8;
		// 子网掩码的补位位数
		int num2 = inetMask % 8;
		int array[] = new int[4];
		for (int i = 0; i < num1; i++) {
			array[i] = 255;
		}
		for (int i = num1; i < 4; i++) {
			array[i] = 0;
		}
		for (int i = 0; i < num2; num2--) {
			array[num1] += 1 << 8 - num2;
		}
		for (int i = 0; i < 4; i++) {
			if (i == 3) {
				mask.append(array[i]);
			} else {
				mask.append(array[i] + ".");
			}
		}
		return mask.toString();
	}
 
	/**
	 * 根据网段计算起始IP 网段格式:x.x.x.x/x
	 * 一个网段0一般为网络地址,255一般为广播地址.
	 * 起始IP计算:网段与掩码相与之后加一的IP地址
	 * @param segment 网段
	 * @return 起始IP
	 */
	public static String getStartIp(String segment) {
		StringBuffer startIp = new StringBuffer();
		if (segment == null) {
			return null;
		}
		String arr[] = segment.split("/");
		String ip = arr[0];
		String maskIndex = arr[1];
		String mask = IpCaculate.getNetMask(maskIndex);
		if (4 != ip.split("\\.").length || mask == null) {
			return null;
		}
		int ipArray[] = new int[4];
		int netMaskArray[] = new int[4];
		for (int i = 0; i < 4; i++) {
			try {
				ipArray[i] = Integer.parseInt(ip.split("\\.")[i]);
				netMaskArray[i] = Integer.parseInt(mask.split("\\.")[i]);
				if (ipArray[i] > 255 || ipArray[i] < 0 || netMaskArray[i] > 255 || netMaskArray[i] < 0) {
					return null;
				}
				ipArray[i] = ipArray[i] & netMaskArray[i];
				if(i==3){
					startIp.append(ipArray[i]+1);
				}else{
					startIp.append(ipArray[i]+".");
				}
			} catch (NumberFormatException e) {
				System.out.println(e.getMessage());
			}
		}
		 return startIp.toString();
	}
	
	/**
	 * 根据网段计算结束IP
	 * @param segment
	 * @return 结束IP
	 */
	public static String getEndIp(String segment) {  
		StringBuffer endIp=new StringBuffer();
		String startIp = getStartIp(segment);  
		if (segment == null) {
			return null;
		}
		String arr[] = segment.split("/");
		String maskIndex = arr[1];
		//实际需要的IP个数
	  int hostNumber = 0;
	  int startIpArray[] = new int[4];
		try {
			hostNumber=1<<32-(Integer.parseInt(maskIndex));
			for (int i = 0; i <4; i++) {  
				startIpArray[i] = Integer.parseInt(startIp.split("\\.")[i]);  
		    if(i == 3){  
		    	startIpArray[i] = startIpArray[i] - 1;  
		      break;
		    }  
		  }  
			startIpArray[3] = startIpArray[3] + (hostNumber - 1); 
		} catch (NumberFormatException e) {
			System.out.println(e.getMessage());
		}
	  
		if(startIpArray[3] >255){  
	    int k = startIpArray[3] / 256;  
	    startIpArray[3] = startIpArray[3] % 256;  
	    startIpArray[2] = startIpArray[2] + k;  
	  }  
	  if(startIpArray[2] > 255){  
	    int j = startIpArray[2] / 256;  
	    startIpArray[2] = startIpArray[2] % 256;  
	    startIpArray[1] = startIpArray[1] + j;  
	      if(startIpArray[1] > 255){  
	        int k = startIpArray[1] / 256;  
	        startIpArray[1] = startIpArray[1] % 256;  
	        startIpArray[0] = startIpArray[0] + k;  
	      }  
	    }  
	  for(int i = 0; i < 4; i++){  
	    if(i == 3){  
	    	startIpArray[i] = startIpArray[i] - 1;  
	    }  
	    if("" == endIp.toString()||endIp.length()==0){  
	    	endIp.append(startIpArray[i]);  
	    }else{  
	    	endIp.append("." + startIpArray[i]);  
	    }  
	  }  
		return endIp.toString();
	} 
}

根据网段计算起始IP 网段格式:x.x.x.x/x

网段内需要的IP数量为:2的(32-掩码位)次方个。

因为一个网段0一般为网络地址,255一般为广播地址, 所以第一个可用IP起始IP计算:网段与掩码相与之后加一的IP地址,结束IP为通过计算需要的所有IP数然后做累加运算,超过256则进位进行运算。

到此这篇关于java IP地址网段计算的示例代码的文章就介绍到这了,更多相关java IP地址计算内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文