【问题标题】:Java - Print random IP addresses in a given rangeJava - 打印给定范围内的随机 IP 地址
【发布时间】: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?

提前致谢。

【问题讨论】:

    标签: java ip range


    【解决方案1】:

    您可以按照以下步骤实现:

    1. 转换两个IPs to numeric values
    InetAddress i= InetAddress.getByName(IPString);
    int intRepresentation= ByteBuffer.wrap(i.getAddress()).getInt();
    
    1. 生成random between the limits
    r.nextInt(High-Low) + Low;
    
    1. 将结果转换回numeric to IP
    i= InetAddress.getByName(String.valueOf(intRepresentation));
    String ip= i.getHostAddress();
    

    【讨论】:

    • 这种方法可以正常工作,直到最大值为 128.255.255.255。保留其返回的负值并导致以下异常: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) .....
    • @Forece85 转换为 long 而非参见 stackoverflow.com/questions/10087800/…
    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 2017-05-28
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多