java 根据给定的子网掩码和网关计算起始IP和结束IP

java 根据给定的子网掩码和网关计算起始IP和结束IP

以下是一个Java工具类,用于根据给定的子网掩码和网关计算起始IP和结束IP。

java 复制代码
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPUtils {
    public static void main(String[] args) {
        try {
            String subnetMask = "255.255.255.0";
            String gateway = "192.168.1.1";
            String startIp = calculateStartIp(subnetMask, gateway);
            String endIp = calculateEndIp(subnetMask, gateway);

            System.out.println("Start IP: " + startIp);
            System.out.println("End IP: " + endIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static String calculateStartIp(String subnetMask, String gateway) throws UnknownHostException {
        byte[] subnetMaskBytes = InetAddress.getByName(subnetMask).getAddress();
        byte[] gatewayBytes = InetAddress.getByName(gateway).getAddress();

        byte[] startIpBytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            startIpBytes[i] = (byte) (gatewayBytes[i] & subnetMaskBytes[i]);
        }

        return InetAddress.getByAddress(startIpBytes).getHostAddress();
    }

    public static String calculateEndIp(String subnetMask, String gateway) throws UnknownHostException {
        byte[] subnetMaskBytes = InetAddress.getByName(subnetMask).getAddress();
        byte[] gatewayBytes = InetAddress.getByName(gateway).getAddress();

        byte[] endIpBytes = new byte[4];
        for (int i = 0; i < 4; i++) {
            endIpBytes[i] = (byte) ((gatewayBytes[i] & subnetMaskBytes[i]) | (subnetMaskBytes[i] ^ 255));
        }

        return InetAddress.getByAddress(endIpBytes).getHostAddress();
    }
}

使用上述工具类,您可以通过修改subnetMaskgateway变量来计算起始IP和结束IP。

相关推荐
another heaven17 小时前
【Qt VS2022调试时无法查看QString等Qt变量信息】解决方法
开发语言·qt
A黄俊辉A17 小时前
axios+ts封装
开发语言·前端·javascript
异常驯兽师17 小时前
Spring 中处理 HTTP 请求参数注解全解析
java·spring·http
连合机器人18 小时前
晨曦中的守望者:当科技为景区赋予温度
java·前端·科技
杨福瑞18 小时前
C语⾔内存函数
c语言·开发语言
AD钙奶-lalala18 小时前
idea新建的项目new 没有java class选项
java·ide·intellij-idea
eqwaak018 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
axban18 小时前
QT M/V架构开发实战:QStringListModel介绍
开发语言·数据库·qt
刘媚-海外18 小时前
Go语言开发AI应用
开发语言·人工智能·golang·go
sheji341618 小时前
【开题答辩全过程】以 12306候补购票服务系统为例,包含答辩的问题和答案
java·eclipse