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。

相关推荐
AI进化营-智能译站3 小时前
ROS2 C++开发系列17-多线程驱动多传感器|chrono高精度计时实现机器人同步控制
java·c++·ai·机器人
天若有情6737 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
qq_589568107 小时前
springbootweb案例,出现访问 http://localhost:8080/list 一直处于浏览器运转阶段
java·网络协议·http·list·springboot
JAVA面经实录9177 小时前
计算机基础(完整版·超详细可背诵)
java·linux·数据结构·算法
特种加菲猫7 小时前
继承,一场跨越时空的对话
开发语言·c++
AC赳赳老秦7 小时前
知识产权辅助:用 OpenClaw 批量生成专利交底书 / 软著申请材料,自动校验格式与内容合规性
java·人工智能·python·算法·elasticsearch·deepseek·openclaw
代码中介商7 小时前
Linux TCP 网络编程完全指南:从三次握手到高并发服务器
服务器·网络·tcp/ip
FYKJ_20108 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
玩转单片机与嵌入式8 小时前
玩转边缘AI(TInyML):需要掌握的C++知识汇总!
开发语言·c++·人工智能