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。

相关推荐
汤米粥5 分钟前
Python爬虫中Xpath用法之——normalize-space()
开发语言·python
FREEDOM_X11 分钟前
Linux 多线程编程——总结
java·linux·运维·ubuntu
科技道人14 分钟前
记录 设置-显示大小和字体
开发语言·android设置·字体和显示大小
tmlx3I08120 分钟前
Tomcat的架构设计和启动过程详解
java·tomcat
浮江雾22 分钟前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
weixin_4223293128 分钟前
AgentScope Java 项目入门 & Builder 深度解读
java·开发语言·人工智能
shepherd12631 分钟前
一次把 Spring MVC 文件上传参数“查没了”的排查:multipart、Filter 与 request body 的连环坑
java·后端·spring·mvc
宠友信息41 分钟前
Spring Boot与异步审核构建仿小红书源码内容发布全流程
java·数据库·spring boot·redis·mysql·oracle·uni-app
chh56343 分钟前
C++--list
开发语言·数据结构·c++·学习·算法·list
Listen·Rain1 小时前
Springboot整合RedisStack
java·spring boot·redis