生成随机 IP 地址

发布于 2025-01-04 07:42:15 字数 1289 浏览 0 评论 0原文

我想生成一些随机 IP 地址。但每次这个generateIPAddress函数都会返回0.0.0.0字符串作为ipAddress。但它应该每次都返回一些随机的 ipAddress,而不是 0.0.0.0。有什么建议吗?为什么会发生这种情况?

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 方法,

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

}

我想要以p1,p2,p3 的形式分配给ipAddress 的随机值,最后一位应该是0

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;
            }
        }
    }
}

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

}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

千寻… 2025-01-11 07:42:15
Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
Random r = new Random();
return r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
梦中楼上月下 2025-01-11 07:42:15

使用 Google Guava

import com.google.common.net.InetAddresses;
...
String ipString = InetAddresses.fromInteger(random.nextInt()).getHostAddress();

当然,您可以验证结果地址不进行多播等。

Using Google Guava:

import com.google.common.net.InetAddresses;
...
String ipString = InetAddresses.fromInteger(random.nextInt()).getHostAddress();

of course you can validate the resulting address not to be multicast etc.

鹿港小镇 2025-01-11 07:42:15

我最近开发了一个 小型库,它可以使用不同类型约束生成随机 IPv4 地址:

MockNeat mock = MockNeat.threadLocal();

String ipv4 = mock.ipv4s().val();
System.out.println(ipv4);

String ipClassA = mock.ipv4s().type(CLASS_A).val();
System.out.println(ipClassA);

String classAorB = mock.ipv4s().types(CLASS_A, CLASS_B).val();
System.out.println(classAorB);

List<String> ip4s = mock.ipv4s().list(10).val();
System.out.println(ip4s);

输出:

192.112.222.183
120.178.110.193
143.68.176.47
[112.246.76.178, 29.201.72.151, 67.105.2.128, 102.189.109.206, 157.146.176.212, 59.220.145.35, 47.171.185.233, 162.245.163.124, 19.203.21.194, 114.177.238.50]

I've recently developed a small library that can generate random IPv4 addresses using different type constraints:

MockNeat mock = MockNeat.threadLocal();

String ipv4 = mock.ipv4s().val();
System.out.println(ipv4);

String ipClassA = mock.ipv4s().type(CLASS_A).val();
System.out.println(ipClassA);

String classAorB = mock.ipv4s().types(CLASS_A, CLASS_B).val();
System.out.println(classAorB);

List<String> ip4s = mock.ipv4s().list(10).val();
System.out.println(ip4s);

Output:

192.112.222.183
120.178.110.193
143.68.176.47
[112.246.76.178, 29.201.72.151, 67.105.2.128, 102.189.109.206, 157.146.176.212, 59.220.145.35, 47.171.185.233, 162.245.163.124, 19.203.21.194, 114.177.238.50]
江湖彼岸 2025-01-11 07:42:15

假设您实际上并不关心生成的 IP 地址以任何形式有效,那么您会遇到一个简单的问题。

用于生成地址的代码将参数 p3p2 设置为小于 255 的值。 p1 被困在 2550 之间。

真正的问题是,将其转换为地址的代码会改变这些值。 p124p216p38< /代码>。了解调用方法中应用的限制,您可以知道 p1p2p3 永远不会超过 255 ,因此在这种情况下,知道 8 或更多的移位将导致 0,地址的任何单个元素都不会导致 以外的值0,最后一个八位字节始终是0,所以结果地址将是0.0.0.0

如果你想防止它是0.0.0.0,首先要做的是删除移位操作。这仍会将最后一个字段保留为 0,因为它从未被设置,但它应该生成地址。

同样,这并不关心地址的状态,使用此方法您最终将获得广播、多播和仅限本地地址。

Assuming that you don't actually care about the resultant IP address being valid in any form whatsoever, you have a simple problem.

The code for generating the addresses sets the parameters p3 and p2 to something less than 255. p1 is trapped between 255 and 0.

The real problem is that the code that turns this into an address shifts these values. p1 by 24, p2 by 16 and p3 by 8. Understanding the limitation applied in the calling method, you can know that p1, p2 and p3 will never exceed 255, so in this case knowing that a shift of 8 or more will result in 0, none of the individual elements of the address will result in a value other than 0, and the last octet will always be 0, so the resultant address will be 0.0.0.0

If you want to prevent it from being 0.0.0.0, the first thing to do is remove the shift operations. This will still keep the last field as 0, because it is never set, but it should produce addresses.

Again, this is not caring about the state of the addresses, you will end up with broadcast, multicast and local-only addresses using this method.

酒几许 2025-01-11 07:42:15

当您调用 generateIPAddress(p1, p2, p3) 时,p1255p2p30

该行将

int b1 = (p1 >> 24) & 0xff;

p1 右移 24 位。轮班前,p111111111。移位结果为 0。实际上您也可以使用

int b1 = p1 >> 8;

,因为 p1 仅打开了 8 个最低有效位。 &的使用0xff 是多余的,因为该操作是在两个 int 操作数之间进行的。所以b10

p2p3 使用值 0 传递,因此移位(通过 168< /code>) 不会改变它一点点,导致 b2b3 也是 0

b4 显式设置为 0

因此,所有 b1b2b3b4 都是 0,从中您可以创建 ip1ip4。因此,方法 generateIPAddress(p1, p2, p3) 始终返回 0.0.0.0

然后 p3 += inc;5 添加到 0p3 中的 Reuslt 现在为 5

条件 if (p3 > 255) 始终会失败,因为 p35,即 <;第255章 ……

When you invoke generateIPAddress(p1, p2, p3), p1 is 255, p2 and p3 are 0.

This line

int b1 = (p1 >> 24) & 0xff;

shifts p1 24 bits to the right. Before the shift p1 was 11111111. The shift results with 0. Actually you could also use

int b1 = p1 >> 8;

as p1 has only its 8 least significant bits turned on. The use of & 0xff is redundant as the operation is between two int operands. So b1 is 0.

p2 and p3 are passed with the value 0 so the shift (either by 16 or 8) doesn't change it one bit, resulting with b2 and b3 being also 0.

b4 is explicitly set to 0.

So all b1, b2, b3 and b4 are 0, from which you create ip1 to ip4. So the method generateIPAddress(p1, p2, p3) always returns 0.0.0.0.

Then p3 += inc; adds 5 to 0. Reuslt in p3 now is 5.

The condition if (p3 > 255) will always fail as p3 is 5 which is < 255...

温柔戏命师 2025-01-11 07:42:15

要使用子网掩码生成随机 IP 地址,请使用以下代码(请注意,在此代码中子网掩码具有 CIDR 格式):

import java.util.Random;
import java.util.Scanner;

public class mainClas {

    public static int findRange(int mask)
    {
        int x = 8 - mask;
        int sum = 0;
        for (int i = 0 ; i < x ; i++) {
            sum += Math.pow(2 , i);
        }
        return sum;
    }

    public static int findFixedPart(String IPPrefix, int i)
    {
        String f = IPPrefix.split("\\.")[i];
        return Integer.valueOf(f);
    }

    public static String generateRandomIP(String IPPrefix, Integer mask)
    {
        String IP="";
        Random r = new Random();
        if (mask < 8)
            IP = (findFixedPart(IPPrefix, 0) + r.nextInt(findRange(mask))) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >7 && mask < 16)
            IP = findFixedPart(IPPrefix, 0) + "." + (findFixedPart(IPPrefix, 1) + r.nextInt(findRange(mask-8))) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >15 && mask < 24)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + (findFixedPart(IPPrefix, 2) + r.nextInt(findRange(mask-16))) + "." + r.nextInt(256);
        else if (mask >23 && mask < 33)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + findFixedPart(IPPrefix, 2) + "." + (findFixedPart(IPPrefix, 3) + r.nextInt(findRange(mask-24)));
        return IP;
    }

    public static void main(String[] inpout)
    {

        System.out.println("Enter IP Prefix: ");
        Scanner sc = new Scanner(System.in);
        String IPPrefix = sc.nextLine();
        System.out.println("Enter Mask: ");
        Integer mask = sc.nextInt();

        // Find random IP in Subnet mask
        String IP = generateRandomIP(IPPrefix, mask);
        System.out.println(IP);
    }
}

To generate random IP address with Subnet Mask use the below code (Note that in this code Subnet Mask has CIDR format):

import java.util.Random;
import java.util.Scanner;

public class mainClas {

    public static int findRange(int mask)
    {
        int x = 8 - mask;
        int sum = 0;
        for (int i = 0 ; i < x ; i++) {
            sum += Math.pow(2 , i);
        }
        return sum;
    }

    public static int findFixedPart(String IPPrefix, int i)
    {
        String f = IPPrefix.split("\\.")[i];
        return Integer.valueOf(f);
    }

    public static String generateRandomIP(String IPPrefix, Integer mask)
    {
        String IP="";
        Random r = new Random();
        if (mask < 8)
            IP = (findFixedPart(IPPrefix, 0) + r.nextInt(findRange(mask))) + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >7 && mask < 16)
            IP = findFixedPart(IPPrefix, 0) + "." + (findFixedPart(IPPrefix, 1) + r.nextInt(findRange(mask-8))) + "." + r.nextInt(256) + "." + r.nextInt(256);
        else if (mask >15 && mask < 24)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + (findFixedPart(IPPrefix, 2) + r.nextInt(findRange(mask-16))) + "." + r.nextInt(256);
        else if (mask >23 && mask < 33)
            IP = findFixedPart(IPPrefix, 0) + "." + findFixedPart(IPPrefix, 1)  + "." + findFixedPart(IPPrefix, 2) + "." + (findFixedPart(IPPrefix, 3) + r.nextInt(findRange(mask-24)));
        return IP;
    }

    public static void main(String[] inpout)
    {

        System.out.println("Enter IP Prefix: ");
        Scanner sc = new Scanner(System.in);
        String IPPrefix = sc.nextLine();
        System.out.println("Enter Mask: ");
        Integer mask = sc.nextInt();

        // Find random IP in Subnet mask
        String IP = generateRandomIP(IPPrefix, mask);
        System.out.println(IP);
    }
}
白日梦 2025-01-11 07:42:15

这个函数将帮助你生成无限数量的随机IP地址:

        StringBuilder ip = new StringBuilder("xx.xx.xx.xx");
            for (int i=0 ; i <11;i++){

                if (i==2){}
                else if (i==5){}
                else if (i==8){}
                else{
                    Random r = new Random();
                    int random = r.nextInt((9 - 1) + 1) + 1;
                    char c = (char)(random+'0');
                    ip.setCharAt(i, c);
                }

            }

            Log.v("ip","Server IP : "+ip);

正如你所看到的,我生成了xx.xx.xx.xx ip格式,你可以处理它来生成任何ip格式。

this function will help you to generate an infinite number of a random IP address:

        StringBuilder ip = new StringBuilder("xx.xx.xx.xx");
            for (int i=0 ; i <11;i++){

                if (i==2){}
                else if (i==5){}
                else if (i==8){}
                else{
                    Random r = new Random();
                    int random = r.nextInt((9 - 1) + 1) + 1;
                    char c = (char)(random+'0');
                    ip.setCharAt(i, c);
                }

            }

            Log.v("ip","Server IP : "+ip);

As you see i generate xx.xx.xx.xx ip format and you can handle it to generate any ip format.

那请放手 2025-01-11 07:42:15

我编写了一个简短的代码来过滤 wikipedia 中列出的特殊范围(稍微多一点)仅基于第一个八位位组):

Random r = new Random();
Integer prefix;
while ({
    prefix = r.nextInt(256);
    prefix in [0,10,100,127,172,192,198,203,224,240,255]
}());   
return prefix + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);

I wrote a short code to filter out ranges listed in wikipedia as special (slightly more as only based on 1st octet):

Random r = new Random();
Integer prefix;
while ({
    prefix = r.nextInt(256);
    prefix in [0,10,100,127,172,192,198,203,224,240,255]
}());   
return prefix + "." + r.nextInt(256) + "." + r.nextInt(256) + "." + r.nextInt(256);
红ご颜醉 2025-01-11 07:42:15

生成随机 IP 地址的一种非常简单快速的方法:

import java.util.Random;

public class IpAddressHelper {

     public static String createRandom() {
         return randomNumber() + "." + randomNumber() + "." + randomNumber() + "." + randomNumber();
     }

     public static int randomNumber() {
         return new Random().nextInt((255 - 1) + 1) + 1;
     }
}

A very simple and fast way to generate a random ip address:

import java.util.Random;

public class IpAddressHelper {

     public static String createRandom() {
         return randomNumber() + "." + randomNumber() + "." + randomNumber() + "." + randomNumber();
     }

     public static int randomNumber() {
         return new Random().nextInt((255 - 1) + 1) + 1;
     }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文