当前位置: 首页 > news >正文

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

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

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

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。


http://www.mrgr.cn/news/18041.html

相关文章:

  • Unity(2022.3.41LTS) - UI详细介绍- Button(按钮)TMP
  • 【类模板】类模板的特化
  • 金九银十来了,你准备好了吗?——迎接技术行业的旺季
  • SPI驱动学习三(spidev的使用)
  • 【C语言从不挂科到高绩点】06-流程控制语句-循环语句
  • 万亿秒查是真地吗?比 ORACLE 快 N 倍是不是吹牛?
  • 轻量级 AI 革命:Phi-3.5 小模型现可一键 input!浙大领头开源多模态基准上线,含 8 大类别图像问答
  • 点击刷新按钮或者按 F5、按 Ctrl+F5 (强制刷新)、地址栏回车有什么区别?
  • 青书学堂 看视频 看课时 php 懒人版
  • Spring Boot启动卡在Root WebApplicationContext: initialization completed in...
  • 换毛季来临,猫咪浮毛如何快速清理?好用的宠物空气净化器推荐
  • 网工面试题(安全)
  • kafka3.7.1 单节点 KRaft部署测试发送和接收消息
  • 2024java面试题
  • 古典显示格式解一偏微分方程并绘制结果的彩色图
  • ~/.bashrc、 ~/.bash_profile、~/.profile、 /etc/profile几个配置文件的区别
  • 【408DS算法题】033基础-判断二叉树是否是二叉排序树
  • 云计算实训40——部署nmt、部署project_exam_system项目
  • 帧中继了解
  • Centos安装node_exporter