生成随机IP地址 [英] Generate Random IP Address

查看:453
本文介绍了生成随机IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一些随机IP地址。但是evertime这个generateIPAddress函数返回0.0.0.0字符串作为ipAddress。但它应该每次返回一些除0.0.0.0以外的随机ipAddress。有什么建议吗?

I want to generate some random IP Address. But evertime this generateIPAddress function returns 0.0.0.0 string as ipAddress. But it should be returning some random ipAddress other than 0.0.0.0 everytime. Any suggestions why is it happening?

private void callingGeoService() {
    int p1 = 255;
    int p2 = 0;
    int p3 = 0;
    int inc = 5;

    String ipAddress = generateIPAddress(p1, p2, p3);

    p3 += inc;
    if (p3 > 255) {
        p3 = 0;
        p2 += inc;
        if (p2 > 255) {
            p2 = 0;
            p1--;
            if (p1 <= 0) {
                p1 = 0;
            }
        }
    }
}

这个是generateIPAddress方法

This is the generateIPAddress method

private String generateIPAddress(int p1, int p2, int p3) {

    StringBuilder sb = null;

    int b1 = (p1 >> 24) & 0xff;
    int b2 = (p2 >> 16) & 0xff;
    int b3 = (p3 >>  8) & 0xff;
    int b4 = 0;

    String ip1 = Integer.toString(b1);
    String ip2 = Integer.toString(b2);
    String ip3 = Integer.toString(b3);
    String ip4 = Integer.toString(b4);

    //Now the IP is b1.b2.b3.b4
    sb = new StringBuilder();
    sb.append(ip1).append(".").append(ip2).append(".").append(ip3).append(".").append(ip4);
    // System.out.println(sb);

    return sb.toString();

}

我想要一个分配给 ipAddress ,格式为 p1,p2,p3 ,最后一位应为 0

I want a random value assigned to ipAddress in the form of p1,p2,p3 and last bit should be 0.

推荐答案

Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);

这篇关于生成随机IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆