なんだろうけど、日本人には、java部品をチェック場合はIPアドレスから特定のネットワーク/ネット?[定休日]

StackOverflow https://stackoverflow.com/questions/577363

  •  05-09-2019
  •  | 
  •  

質問

い決定が変更されていない場合はIPアドレスから特殊なネットワークが必要な動します。

役に立ちましたか?

解決

Apache Commons純org.apache.commons.net.util.SubnetUtils が表示されます。うんて思ったこと。

SubnetInfo subnet = (new SubnetUtils("10.10.10.0", "255.255.255.128")).getInfo();
boolean test = subnet.isInRange("10.10.10.10");

としては、 カーソン 指摘するApache Commonsネ バグ できなくなるように正しい答える場合があります。カーソンとのSVNバージョンでこのバグを回避するため.

他のヒント

オプション1:

使用 spring-security-web's IpAddressMatcher.とは異なりApache Commons純についても支援を行っていipv4とipv6対応します。

import org.springframework.security.web.util.matcher.IpAddressMatcher;
...

private void checkIpMatch() {
    matches("192.168.2.1", "192.168.2.1"); // true
    matches("192.168.2.1", "192.168.2.0/32"); // false
    matches("192.168.2.5", "192.168.2.0/24"); // true
    matches("92.168.2.1", "fe80:0:0:0:0:0:c0a8:1/120"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/120"); // true
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/128"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "192.168.2.0/32"); // false
}

private boolean matches(String ip, String subnet) {
    IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(subnet);
    return ipAddressMatcher.matches(ip);
}

オプション2(軽量解決!):

コードの前部にコンビニエンスストアでのお支細 そのニーズ spring-security-web が含まれていた。

いないなどの春の枠組みお客様のプロジェクトをご利用いただくことがこのクラスは若干の修理技術のデモンストレーションの 独自のクラス 春からではJDKの依存関係.

/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Matches a request based on IP Address or subnet mask matching against the remote
 * address.
 * <p>
 * Both IPv6 and IPv4 addresses are supported, but a matcher which is configured with an
 * IPv4 address will never match a request which returns an IPv6 address, and vice-versa.
 *
 * @author Luke Taylor
 * @since 3.0.2
 * 
 * Slightly modified by omidzk to have zero dependency to any frameworks other than the JDK.
 */
public final class IpAddressMatcher {
    private final int nMaskBits;
    private final InetAddress requiredAddress;

    /**
     * Takes a specific IP address or a range specified using the IP/Netmask (e.g.
     * 192.168.1.0/24 or 202.24.0.0/14).
     *
     * @param ipAddress the address or range of addresses from which the request must
     * come.
     */
    public IpAddressMatcher(String ipAddress) {

        if (ipAddress.indexOf('/') > 0) {
            String[] addressAndMask = ipAddress.split("/");
            ipAddress = addressAndMask[0];
            nMaskBits = Integer.parseInt(addressAndMask[1]);
        }
        else {
            nMaskBits = -1;
        }
        requiredAddress = parseAddress(ipAddress);
        assert  (requiredAddress.getAddress().length * 8 >= nMaskBits) :
                String.format("IP address %s is too short for bitmask of length %d",
                        ipAddress, nMaskBits);
    }

    public boolean matches(String address) {
        InetAddress remoteAddress = parseAddress(address);

        if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
            return false;
        }

        if (nMaskBits < 0) {
            return remoteAddress.equals(requiredAddress);
        }

        byte[] remAddr = remoteAddress.getAddress();
        byte[] reqAddr = requiredAddress.getAddress();

        int nMaskFullBytes = nMaskBits / 8;
        byte finalByte = (byte) (0xFF00 >> (nMaskBits & 0x07));

        // System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask));

        for (int i = 0; i < nMaskFullBytes; i++) {
            if (remAddr[i] != reqAddr[i]) {
                return false;
            }
        }

        if (finalByte != 0) {
            return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte);
        }

        return true;
    }

    private InetAddress parseAddress(String address) {
        try {
            return InetAddress.getByName(address);
        }
        catch (UnknownHostException e) {
            throw new IllegalArgumentException("Failed to parse address" + address, e);
        }
    }
}

Diff:

+ * 
+ * Slightly modified by omidzk to have zero dependency to any frameworks other than the JDK.

-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.security.web.util.matcher.RequestMatcher;
-import org.springframework.util.StringUtils;
-import org.springframework.util.Assert;

-public final class IpAddressMatcher implements RequestMatcher {
+public final class IpAddressMatcher {

-           String[] addressAndMask = StringUtils.split(ipAddress, "/");
+           String[] addressAndMask = ipAddress.split("/");

-       Assert.isTrue(requiredAddress.getAddress().length * 8 >= nMaskBits,
+       assert  (requiredAddress.getAddress().length * 8 >= nMaskBits) :

-                       ipAddress, nMaskBits));
+                       ipAddress, nMaskBits);

-
-   public boolean matches(HttpServletRequest request) {
-       return matches(request.getRemoteAddr());
-   }

通知:注意すべきことはこのオプションを使用ではお客様の責任を注意深く点検したうえで ライセンス ずこのコードはありません違反条件によって義務付けられている、上記ライセンスです。(もちろんこの出版コードStackoverflow.com 私は侵害となります。)

また、試すことができます。

boolean inSubnet = (ip & netmask) == (subnet & netmask);

または短い

boolean inSubnet = (ip ^ subnet) & netmask == 0;

サブネット内のアンIPを確認するには、私はSubnetUtilsクラスのisInRangeメソッドを使用していました。しかし、この方法では、あなたのサブネットがX、Xよりも低く、trueを返しisInRangeすべてのIPアドレスだった場合、バグを持っています。たとえば、あなたのサブネットが10.10.30.0/24だった、あなたは、このメソッドはtrueを返し10.10.20.5を確認したい場合。私はコードの下に使用されるこのバグに対処する。

public static void main(String[] args){
    String list = "10.10.20.0/24";
    String IP1 = "10.10.20.5";
    String IP2 = "10.10.30.5";
    SubnetUtils  subnet = new SubnetUtils(list);
    SubnetUtils.SubnetInfo subnetInfo = subnet.getInfo();
    if(MyisInRange(subnetInfo , IP1) == true)
       System.out.println("True");
    else 
       System.out.println("False");
    if(MyisInRange(subnetInfo , IP2) == true)
       System.out.println("True");
    else
       System.out.println("False");
}

private boolean MyisInRange(SubnetUtils.SubnetInfo info, String Addr )
{
    int address = info.asInteger( Addr );
    int low = info.asInteger( info.getLowAddress() );
    int high = info.asInteger( info.getHighAddress() );
    return low <= address && address <= high;
}

ここプレフィックスとネットワークマスクを持つ1でIPv4とIPv6の1で動作するバージョンがあります。

/**
 * Check if IP is within an Subnet defined by Network Address and Network Mask
 * @param  ip
 * @param  net
 * @param  mask
 * @return
 */
public static final boolean isIpInSubnet(final String ip, final String net, final int prefix) {
    try {
        final byte[] ipBin   = java.net.InetAddress.getByName(ip  ).getAddress();
        final byte[] netBin  = java.net.InetAddress.getByName(net ).getAddress();
        if(ipBin.length  != netBin.length ) return false;
        int p = prefix;
        int i = 0;
        while(p>=8) { if(ipBin[i] != netBin[i] ) return false; ++i; p-=8; }
        final int m = (65280 >> p) & 255;
        if((ipBin[i] & m) != (netBin[i]&m) ) return false;

        return true;
    } catch(final Throwable t) {
        return false;
    }
}

/**
 * Check if IP is within an Subnet defined by Network Address and Network Mask
 * @param  ip
 * @param  net
 * @param  mask
 * @return
 */
public static final boolean isIpInSubnet(final String ip, final String net, final String mask) {
    try {
        final byte[] ipBin   = java.net.InetAddress.getByName(ip  ).getAddress();
        final byte[] netBin  = java.net.InetAddress.getByName(net ).getAddress();
        final byte[] maskBin = java.net.InetAddress.getByName(mask).getAddress();
        if(ipBin.length  != netBin.length ) return false;
        if(netBin.length != maskBin.length) return false;
        for(int i = 0; i < ipBin.length; ++i) if((ipBin[i] & maskBin[i]) != (netBin[i] & maskBin[i])) return false;
        return true;
    } catch(final Throwable t) {
        return false;
    }
}

ごきげんよう、トメ子ですのもとを義務付けられているものの、見本を探していたときの解決に同じ問題です。

はありま コモンズのホームページからダウンロード-math 図書館と私は非常に良い仕事です。ないように注意してください月2019年には、もありませんの更新を図ることができますが、既に成熟します。その利用 maven-中央

での支援とアドレスにより、IPv4とIPv6の両方のスしています。その短い文書の事例かを確認できた場合、アドレスは特定の範囲 IPv4IPv6

例IPv4範囲の確認:

        String input1 = "192.168.1.0";
        Ipv4 ipv41 = Ipv4.parse(input1);

        // Using CIDR notation to specify the networkID and netmask
        Ipv4Range range = Ipv4Range.parse("192.168.0.0/24");
        boolean result = range.contains(ipv41);
        System.out.println(result); //false

        String input2 = "192.168.0.251";
        Ipv4 ipv42 = Ipv4.parse(input2);

        // Specifying the range with a start and end.
        Ipv4 start = Ipv4.of("192.168.0.0");
        Ipv4 end = Ipv4.of("192.168.0.255");
        range = Ipv4Range.from(start).to(end);

        result = range.contains(ipv42); //true
        System.out.println(result);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top