1. 程式人生 > 其它 >IP網段拆分出多個IP

IP網段拆分出多個IP

package com.lzk.test01.test;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class IpTest1 {
    public static void main(String[] args) throws Exception {
        String demo = "1.0.1.5-2.0.2.4";
        String[] split = demo.split("-");
        String ip1 = split[0];
        String ip2 
= split[1]; //todo 校驗ip格式 if (ip1.equals(ip2)) { System.out.println("ip網段不能相同"); } String[] split1 = ip1.split("\\."); String[] split2 = ip2.split("\\."); int aNum = 0, bNum = 0, cNum = 0, dNum = 0; boolean aBoolean = split1[0].equals(split2[0]);
boolean bBoolean = split1[1].equals(split2[1]); boolean cBoolean = split1[2].equals(split2[2]); boolean dBoolean = split1[3].equals(split2[3]); int a1 = Integer.parseInt(split1[0]); int a2 = Integer.parseInt(split2[0]); int b1 = Integer.parseInt(split1[1]);
int b2 = Integer.parseInt(split2[1]); int c1 = Integer.parseInt(split1[2]); int c2 = Integer.parseInt(split2[2]); int d1 = Integer.parseInt(split1[3]); int d2 = Integer.parseInt(split2[3]); if (!aBoolean) { if (a1 > a2) { throw new Exception("ip網段必須從小到大"); } aNum = a2 - a1 + 1; } if (!bBoolean && aBoolean) { if (b1 > b2) { throw new Exception("ip網段必須從小到大"); } bNum = b2 - b1 + 1; } if(aNum > 0){ bNum = 256; } if (!cBoolean && aBoolean && bBoolean) { if (c1 > c2) { throw new Exception("ip網段必須從小到大"); } cNum = c2 - c1 + 1; } if (!dBoolean && aBoolean && bBoolean && cBoolean) { if (d1 > d2) { throw new Exception("ip網段必須從小到大"); } } if(bNum > 0){ cNum = 256; } if (aNum == 0) { aNum = 1; } if (bNum == 0) { bNum = 1; } if (cNum == 0) { cNum = 1; } try { File file = new File("ip.txt"); file.createNewFile(); FileWriter fileWriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(fileWriter); out.write(ip1 + "\r\n"); boolean flag = false; for (int n = 0; n < aNum; n++) { if(flag){ break; } for (int i = 0; i < bNum; i++) { if(flag){ break; } for (int j = 0; j < cNum; j++) { if(flag){ break; } for (int k = 0; k < 256; k++) { d1++; if (d1 == 256) { c1 ++; d1 = 0; } if (c1 == 256) { b1 ++; c1 = 0; } if (b1 == 256) { a1 ++; b1 = 0; } if (a1 > 255) { a1 = 255; } String s = a1 + "." + b1 + "." + c1 + "." + d1; if (s.equals(ip2)) { log.info(a1 + "." + b1 + "." + c1 + "." + d1); out.write(a1 + "." + b1 + "." + c1 + "." + d1 + "\r\n"); flag = true; break; } log.info(a1 + "." + b1 + "." + c1 + "." + d1); out.write(a1 + "." + b1 + "." + c1 + "." + d1 + "\r\n"); } } } } out.flush(); } catch (IOException e) { e.printStackTrace(); } System.out.println("結束"); } }