iputil.java

来自「cwbbs 云网论坛源码」· Java 代码 · 共 69 行

JAVA
69
字号
package com.cloudwebsoft.framework.util;import java.net.UnknownHostException;import java.net.InetAddress;public class IPUtil {    public static int str2Ip(String ip) {        InetAddress address = null;        try {            address = InetAddress.getByName(ip);         }        catch (UnknownHostException e) {            e.printStackTrace();            return 0;        }        byte[] bytes = address.getAddress();         int a, b, c, d;        a = byte2int(bytes[0]);        b = byte2int(bytes[1]);        c = byte2int(bytes[2]);        d = byte2int(bytes[3]);        int result = (a << 24) | (b << 16) | (c << 8) | d;        return result;    }    public static int byte2int(byte b) {        int l = b & 0x07f;        if (b < 0) {            l |= 0x80;        }        return l;    }    public static long ip2long(String ip) {        int ipNum = str2Ip(ip);        return int2long(ipNum);    }    public static long int2long(int i) {        long l = i & 0x7fffffffL;        if (i < 0) {            l |= 0x080000000L;        }        return l;    }    public static String long2ip(long ip) {        int[] b = new int[4];        b[0] = (int) ((ip >> 24) & 0xff);        b[1] = (int) ((ip >> 16) & 0xff);        b[2] = (int) ((ip >> 8) & 0xff);        b[3] = (int) (ip & 0xff);        String x;        Integer p;        p = new Integer(0);        x = p.toString(b[0]) + "." + p.toString(b[1]) + "." + p.toString(b[2]) +            "." + p.toString(b[3]);        return x;    }    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?