JAVA中IP和整数相互转化(含有掩码的计算)
import java.net.InetAddress;
/**
* 用于IP和整数之间的相互转换
* @author Andy.Wang
*
*/
public class IPv4Util {
private final static int INADDRSZ = 4;
/**
* 把IP地址转化为字节数组
* @param ipAddr
* @return byte[]
*/
public static byte[] ipToBytesByInet(String ipAddr) {
try {
return InetAddress.getByName(ipAddr).getAddress();
} catch (Exception e) {
throw new IllegalArgumentException(ipAddr + " is invalid IP");
}
}
/**
* 把IP地址转化为int
* @param ipAddr
* @return int
*/
public static byte[] ipToBytesByReg(String ipAddr) {
byte[] ret = new byte[4];
try {
String[] ipArr = ipAddr.split("\\.");
ret[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
ret[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
ret[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
ret[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);
return ret;
} catch (Exception e) {
throw new IllegalArgumentException(ipAddr + " is invalid IP");
}
}
/**
* 字节数组转化为IP
* @param bytes
* @return int
*/
public static String bytesToIp(byte[] bytes) {
return new StringBuffer().append(bytes[0] & 0xFF).append('.').append(
bytes[1] & 0xFF).append('.').append(bytes[2] & 0xFF)
.append('.').append(bytes[3] & 0xFF).toString();
}
/**
* 根据位运算把 byte[] -> int
* @param bytes
* @return int
*/
public static int bytesToInt(byte[] bytes) {
int addr = bytes[3] & 0xFF;
addr |= ((bytes[2] << 8) & 0xFF00);
addr |= ((bytes[1] << 16) & 0xFF0000);
addr |= ((bytes[0] << 24) & 0xFF000000);
return addr;
}
/**
* 把IP地址转化为int
* @param ipAddr
* @return int
*/
public static int ipToInt(String ipAddr) {
try {
return bytesToInt(ipToBytesByInet(ipAddr));
} catch (Exception e) {
throw new IllegalArgumentException(ipAddr + " is invalid IP");
}
}
/**
* ipInt -> byte[]
* @param ipInt
* @return byte[]
*/
public static byte[] intToBytes(int ipInt) {
byte[] ipAddr = new byte[INADDRSZ];
ipAddr[0] = (byte) ((ipInt >>> 24) & 0xFF);
ipAddr[1] = (byte) ((ipInt >>> 16) & 0xFF);
ipAddr[2] = (byte) ((ipInt >>> 8) & 0xFF);
ipAddr[3] = (byte) (ipInt & 0xFF);
return ipAddr;
}
/**
* 把int->ip地址
* @param ipInt
* @return String
*/
public static String intToIp(int ipInt) {
return new StringBuilder().append(((ipInt >> 24) & 0xff)).append('.')
.append((ipInt >> 16) & 0xff).append('.').append(
(ipInt >> 8) & 0xff).append('.').append((ipInt & 0xff))
.toString();
}
/**
* 把192.168.1.1/24 转化为int数组范围
* @param ipAndMask
* @return int[]
*/
public static int[] getIPIntScope(String ipAndMask) {
String[] ipArr = ipAndMask.split("/");
if (ipArr.length != 2) {
throw new IllegalArgumentException("invalid ipAndMask with: "
+ ipAndMask);
}
int netMask = Integer.valueOf(ipArr[1].trim());
if (netMask < 0 || netMask > 31) {
throw new IllegalArgumentException("invalid ipAndMask with: "
+ ipAndMask);
}
int ipInt = IPv4Util.ipToInt(ipArr[0]);
int netIP = ipInt & (0xFFFFFFFF << (32 - netMask));
int hostScope = (0xFFFFFFFF >>> netMask);
return new int[] { netIP, netIP + hostScope };
}
/**
* 把192.168.1.1/24 转化为IP数组范围
* @param ipAndMask
* @return String[]
*/
public static String[] getIPAddrScope(String ipAndMask) {
int[] ipIntArr = IPv4Util.getIPIntScope(ipAndMask);
return new String[] { IPv4Util.intToIp(ipIntArr[0]),
IPv4Util.intToIp(ipIntArr[0]) };
}
/**
* 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
* @param ipAddr ipAddr
* @param mask mask
* @return int[]
*/
public static int[] getIPIntScope(String ipAddr, String mask) {
int ipInt;
int netMaskInt = 0, ipcount = 0;
try {
ipInt = IPv4Util.ipToInt(ipAddr);
if (null == mask || "".equals(mask)) {
return new int[] { ipInt, ipInt };
}
netMaskInt = IPv4Util.ipToInt(mask);
ipcount = IPv4Util.ipToInt("255.255.255.255") - netMaskInt;
int netIP = ipInt & netMaskInt;
int hostScope = netIP + ipcount;
return new int[] { netIP, hostScope };
} catch (Exception e) {
throw new IllegalArgumentException("invalid ip scope express ip:"
+ ipAddr + " mask:" + mask);
}
}
/**
* 根据IP 子网掩码(192.168.1.1 255.255.255.0)转化为IP段
* @param ipAddr ipAddr
* @param mask mask
* @return String[]
*/
public static String[] getIPStrScope(String ipAddr, String mask) {
int[] ipIntArr = IPv4Util.getIPIntScope(ipAddr, mask);
return new String[] { IPv4Util.intToIp(ipIntArr[0]),
IPv4Util.intToIp(ipIntArr[0]) };
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String ipAddr = "192.168.8.1";
byte[] bytearr = IPv4Util.ipToBytesByInet(ipAddr);
StringBuffer byteStr = new StringBuffer();
for (byte b : bytearr) {
if (byteStr.length() == 0) {
byteStr.append(b);
} else {
byteStr.append("," + b);
}
}
System.out.println("IP: " + ipAddr + " ByInet --> byte[]: [ " + byteStr
+ " ]");
bytearr = IPv4Util.ipToBytesByReg(ipAddr);
byteStr = new StringBuffer();
for (byte b : bytearr) {
if (byteStr.length() == 0) {
byteStr.append(b);
} else {
byteStr.append("," + b);
}
}
System.out.println("IP: " + ipAddr + " ByReg --> byte[]: [ " + byteStr
+ " ]");
System.out.println("byte[]: " + byteStr + " --> IP: "
+ IPv4Util.bytesToIp(bytearr));
int ipInt = IPv4Util.ipToInt(ipAddr);
System.out.println("IP: " + ipAddr + " --> int: " + ipInt);
System.out.println("int: " + ipInt + " --> IP: "
+ IPv4Util.intToIp(ipInt));
String ipAndMask = "192.168.1.1/24";
int[] ipscope = IPv4Util.getIPIntScope(ipAndMask);
System.out.println(ipAndMask + " --> int地址段:[ " + ipscope[0] + ","
+ ipscope[1] + " ]");
System.out.println(ipAndMask + " --> IP 地址段:[ "
+ IPv4Util.intToIp(ipscope[0]) + ","
+ IPv4Util.intToIp(ipscope[1]) + " ]");
String ipAddr1 = "192.168.1.1", ipMask1 = "255.255.255.0";
int[] ipscope1 = IPv4Util.getIPIntScope(ipAddr1, ipMask1);
System.out.println(ipAddr1 + " , " + ipMask1 + " --> int地址段 :[ "
+ ipscope1[0] + "," + ipscope1[1] + " ]");
System.out.println(ipAddr1 + " , " + ipMask1 + " --> IP地址段 :[ "
+ IPv4Util.intToIp(ipscope1[0]) + ","
+ IPv4Util.intToIp(ipscope1[1]) + " ]");
}
}
JAVA中IP和整数相互转化(含有掩码的计算)的更多相关文章
- [转] 有关java中两个整数的交换问题
转载申明:本文主要是用于自己学习使用,为了完善自己的只是框架,没有任何的商业目的. 原文来源:有关Java中两个整数的交换问题 如果侵权,麻烦告之,立刻删除. 在程序开发的过程,要交换两个变量的内容, ...
- Java中最小的整数为什么是-2147483648
Java中最小的整数为什么是-2147483648 假如只有两位来表示数字,第一位是符号位: 00:0 01:1 11:-1,这个是负数,而且是补码,取反为00,加1成为01,就是-1 10:-2,这 ...
- Java中浮点型数据Float和Double进行精确计算的问题
Java中浮点型数据Float和Double进行精确计算的问题 来源 https://www.cnblogs.com/banxian/p/3781130.html 一.浮点计算中发生精度丢失 ...
- 【Java编程】Java中的大整数计算
在上一篇文章中,我们实现了c语言中的大整数的运算,并且用Miller-Rabin算法实现了对大素数的测试.本来我准备用Java代码实现大整数的运算,查了一下资料发现Java中java.math的Big ...
- 按公式产生随机数、java中的重载、递归、有关计算机计算的问题
1.按公式产生随机数x1=(16807*x)%(Integer.MAX_VALUE)x=x1;通过这个公式进行随机数的产生,当产生的数字大于2e+32-2时,在用产生随机数的方式进行数字的输出.主要思 ...
- Java中的高精度整数和高精度小数
在实际编码中,会遇到很多高精度的事例,比如,在计算金钱的时候就需要保留高精度小数,这样计算才不会有太大误差: 在下面的代码中,我们验证了,当两个float型的数字相加,得到的结果和我们的预期结果是有误 ...
- mysql中ip和整数的转换
INET_ATON(expr) 给出一个作为字符串的网络地址的点地址表示,返回一个代表该地址数值的整数.地址可以是4或8比特地址. mysql> SELECT INET_ATON('209.20 ...
- Java中,当表单含有文件上传时,提交数据的如何读取
http://blog.csdn.net/lian_zhihui1984/article/details/6822201
- 018、Java中除法的是用,解决除法计算精度问题
01.代码如下: package TIANPAN; /** * 此处为文档注释 * * @author 田攀 微信382477247 */ public class TestDemo { public ...
随机推荐
- JAG Practice Contest for ACM-ICPC Asia Regional 2016B题【BFS】
题意: 就是公主要逃跑,士兵要抓公主,问你能不能逃跑哇: 思路: 就是终点搞成起点,然后BFS一下就好了,最后枚举一下出口到公主的距离是不是<所有的到士兵的距离: #include <bi ...
- [Xcode 实际操作]一、博主领进门-(1)iOS项目的创建和项目模板的介绍
目录:[Swift]Xcode实际操作 本文将演示iOS项目的创建和项目模板的介绍. [Create a new Xcode project]创建一个新的项目. 在弹出的模板窗口中,显示了所有的项目模 ...
- CSS优先级、CSS选择器、编写CSS时的注意事项
CSS的优先级: 内嵌样式>ID选择器>类选择器>标签选择器 内部样式>内部样式>外部样式 CSS的选择器: 选择器:在 CSS 中,选择器是一种模式,用于选择需要添加样 ...
- nacos启动
nacos下载 https://github.com/alibaba/nacos 1.执行数据库脚本 2.修改配置文件application.propertiesspring.datasource.p ...
- C 语言实例 - 从文件中读取一行
C 语言实例 - 从文件中读取一行 从文件中读取一行. 文件 runoob.txt 内容: $ cat runoob.txt runoob.com google.com 实例 #include < ...
- Java | 基础归纳 | Map.Entry<String, String>
public class Test { private static Map<String,String> student; private static void init() { st ...
- OSPF-1-OSPF的数据库交换(1)
一.OSPF路由器ID(RID) 选举过程: 1.使用router-id id 命令中配置的路由器ID 2.up着的环回接口最大的ip 3.up着的非环回接口最大ip 如果路由器的RID发生了变化 ...
- 简单的Javascript图片延迟加载库Echo.js
简介: 和 Lazy Load 一样,Echo.js 也是一个用于图像延迟加载 JavaScript.不同的是 Lazy Load 是基于 jQuery 的插件,而 Echo.js 不依赖于 jQue ...
- 如何使用LESS 深度定制Bootstrap
一.LESS是什么? Less 是一门 CSS 预处理语言,它扩展了 CSS 语言,增加了变量.Mixin.函数等特性,使 CSS 更易维护和扩展. 中文介绍:http://lesscss.cn/ 有 ...
- 牛客寒假6-G.区间或和
链接:https://ac.nowcoder.com/acm/contest/332/G 题意: 求a|(a+1)|(a+2)|...|(b-1)|b. 思路: 求a-b的差的每一个二进制位 自己也看 ...