简体   繁体   English

Java-打印给定范围内的随机IP地址

[英]Java - Print random IP addresses in a given range

I am trying to get a random ip address from given range. 我正在尝试从给定范围获取随机IP地址。

EX: startIp = "192.168.1.0" ; 例如:startIp =“ 192.168.1.0”; endIp = "192.168.2.255" endIp =“ 192.168.2.255”

I tried of converting range to cidr and getting randomIp for cidr list using SubnetUtils but no luck. 我尝试使用SubnetUtils将范围转换为cidr并为cidr列表获取randomIp,但没有运气。

Is there any effective way of generating a random ip from given ip-range or an api which can do this? 有什么有效的方法可以从给定的ip-range或api生成随机ip吗?

Thanks in advance. 提前致谢。

You can achieve by following the steps: 您可以按照以下步骤操作:

  1. Convert the two IPs to numeric values 将两个IP转换为数值
 InetAddress i= InetAddress.getByName(IPString); int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt(); 
  1. Generate random between the limits 在限制之间产生随机
 r.nextInt(High-Low) + Low; 
  1. Convert result back numeric to IP 将结果转换回数字到IP
 i= InetAddress.getByName(String.valueOf(intRepresentation)); String ip= i.getHostAddress(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM