【发布时间】:2019-02-07 15:24:26
【问题描述】:
我正在尝试从给定范围内获取随机 IP 地址。
EX: startIp = "192.168.1.0" ; endIp = "192.168.2.255"
我尝试使用 SubnetUtils 将范围转换为 cidr 并获取 cidr 列表的 randomIp,但没有运气。
是否有任何有效的方法可以从给定的 ip-range 或可以做到这一点的 api 生成随机 ip?
提前致谢。
【问题讨论】:
我正在尝试从给定范围内获取随机 IP 地址。
EX: startIp = "192.168.1.0" ; endIp = "192.168.2.255"
我尝试使用 SubnetUtils 将范围转换为 cidr 并获取 cidr 列表的 randomIp,但没有运气。
是否有任何有效的方法可以从给定的 ip-range 或可以做到这一点的 api 生成随机 ip?
提前致谢。
【问题讨论】:
您可以按照以下步骤实现:
InetAddress i= InetAddress.getByName(IPString); int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt();
r.nextInt(High-Low) + Low;
i= InetAddress.getByName(String.valueOf(intRepresentation)); String ip= i.getHostAddress();
【讨论】:
Exception in thread "main" java.net.UnknownHostException: -847933385 at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source) at java.net.InetAddress.getAddressesFromNameService(Unknown Source) at java.net.InetAddress.getAllByName0(Unknown Source) at java.net.InetAddress.getAllByName(Unknown Source) .....