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。

相关推荐
毕设源码-邱学长3 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
rookieﻬ°4 小时前
PHP框架漏洞
开发语言·php
炸膛坦客5 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
兑生5 小时前
【灵神题单·贪心】1481. 不同整数的最少数目 | 频率排序贪心 | Java
java·开发语言
daidaidaiyu5 小时前
一文学习 Spring 声明式事务源码全流程总结
java·spring
炸膛坦客6 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
零雲6 小时前
java面试:了解抽象类与接口么?讲一讲它们的区别
java·开发语言·面试
平生幻6 小时前
TCP协议与UDP协议的区别
网络协议·tcp/ip·udp
Jay_Franklin6 小时前
Quarto与Python集成使用
开发语言·python·markdown
2401_831824967 小时前
代码性能剖析工具
开发语言·c++·算法