代码之家  ›  专栏  ›  技术社区  ›  Forece85

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

  •  0
  • Forece85  · 技术社区  · 8 年前

    我试图从给定的范围内随机获取一个ip地址。

    我尝试过将range转换为cidr,并使用SubnetUtils获取cidr列表的randomIp,但没有成功。

    提前谢谢。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ori Marko    8 年前

    您可以通过以下步骤实现:

    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();