集册 Java实例教程 比较两个IP地址字节数组,长度必须是4或16。

比较两个IP地址字节数组,长度必须是4或16。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

569
比较两个IP地址字节数组,长度必须是4或16。


//package com.nowjava;/*来自 n o w j a   v  a . c o m - 时  代  Java*/


public class Main {



    /**

     * Compare two IP address byte array, the length must be 4 or 16.

     * @param address1

     * @param address2

     * @return

     */

    private static boolean ifSameIpAddress(byte[] address1, byte[] address2) {

        if (address1 == null && address2 == null)

            return true;


        if (address1 != null && address2 != null

                && address1.length == address2.length) {

            //this IPv4 address

            if (address1.length == 4) {

                int a = getInteger(address1);

                int b = getInteger(address2);

                return a == b;
                /*
                n o w  j a v a  . c o m 提供
                */

            } else {

                for (int i = 0; i < 16; i++) {

                    if (address1[i] != address2[i])

                        return false;

                }

                return true;

            }

        }


        return false;


    }


    private static int getInteger(byte[] addr) {

        int address = 0;

        if (addr != null) {

            
展开阅读全文