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();
    }
}

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

相关推荐
青山木18 分钟前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
朝朝辞暮i18 分钟前
C++ 第 26 课:对象、指针与 ->
java·开发语言·c++
Zelman20 分钟前
TCP 协议
网络协议·tcp/ip
长弓三石22 分钟前
把 AgentScope Harness 装进 RuoYi-Vue-Plus:纯 Java AI 平台的集成实践
java·人工智能·agent
蜗牛互联网24 分钟前
MongoDB Atlas Agent Engine之后,如何用版本门禁防止陈旧写入
java·数据库·人工智能·后端·mongodb
长弓三石24 分钟前
企业级智能体的权限到底怎么落地?以 BizBuddy 为例
java·人工智能·agent
用户42702767268133 分钟前
一次缓存优化:SQL 从 502 降到 5
java
2601_962885721 小时前
如何用 Python 做股价历史分位选股?(筛出处于历史低位的股票)
开发语言·python
小师兄吃牛肉1 小时前
C语言指针进阶全解析
java·c语言·算法
Joy T1 小时前
聊天系统中五大ID的演进与实战解析
java·前端·人工智能·spring·agent入门