3

Java で IP サブネット マスクを 24 から 255.255.255.0 に、または 23 から 255.255.254.0 に変換する必要があります。使用できる API はありますか?

ありがとう。

4

2 に答える 2

5

Without any libraries :

int cidrMask = 23;
long bits = 0;
bits = 0xffffffff ^ (1 << 32 - cidrMask) - 1;
String mask = String.format("%d.%d.%d.%d", (bits & 0x0000000000ff000000L) >> 24, (bits & 0x0000000000ff0000) >> 16, (bits & 0x0000000000ff00) >> 8, bits & 0xff);

>>255.255.254.0

Have to use a long because of missing unsigned types in Java

于 2013-06-12T15:18:05.537 に答える
0

http://commons.apache.org/proper/commons-net/apidocs/index.html?org/apache/commons/net/util/SubnetUtils.html

NeplatnyUdaj のコメントに従いましたが、SubnetUtils オブジェクトを作成してマスクを取得できるようです。

    int mask = 3;
    String cidr = "255.255.255.255/" + mask;
    SubnetUtils subnet = new SubnetUtils(cidr);

    String stringMask = subnet.getInfo().getNetmask();

    System.out.println("The subnet mask is: " + stringMask);

それが私が使っていたもので、私にとってはうまくいきました。実際、getNetmask() メソッドを使用すると、cidr 文字列の作成に使用する IP 文字列が任意になります。

于 2013-06-12T15:05:15.657 に答える