JAVA 获取机器IP 相关方法

积累点关于Java获取IP 和Host,判断操作系统类型方面的知识,现在多积累点,以后就能直接拿来用多好。

1.获取IP,host用JDK自带的java.net.InetAddress.java来完成

//获取IP
String ipAddress = InetAddress.getLocalHost().getHostAddress();

//获取hostName
String hostName = InetAddress.getLocalHost().getHostName();


//获取canonicalHostName
String canonicalHostName = InetAddress.getLocalHost().getCanonicalHostName();

 后面两个方法的区别是,一个是主机名,一个是主机名的别名

 

2. 判断windows系统的方法

public static boolean isWindows() {
        return System.getProperty("os.name").indexOf("Window") != -1;
    }

 利用JVM的属性来判断

 

3. 将IP地址变为byte数组,下面方法只对IPV4的地址进行转换

public static byte[] parseIPV4Address(String ipAddressStr) throws IllegalArgumentException {
        StringTokenizer tok = new StringTokenizer(ipAddressStr, ".");
        int count = 0;
        byte ipAddressBytes[] = new byte[4];
        while (tok.hasMoreTokens()) {
            String ipAddressPartStr = tok.nextToken();
            int ipAddressPartInt = -1;
            boolean parseError = false;
            try {
                ipAddressPartInt = Integer.parseInt(ipAddressPartStr);
            } catch (NumberFormatException e) {
                parseError = true;
            }
            if (parseError || ipAddressPartInt > 255)
                throw new IllegalArgumentException((new StringBuilder()).append("String \"").append(ipAddressPartStr)
                        .append("\" does not contain a valid byte integer value").toString());
            byte ipAddressPart = (byte) ipAddressPartInt;
            if (count >= 4)
                throw new IllegalArgumentException((new StringBuilder()).append("String \"").append(ipAddressPartStr)
                        .append("\" does not contain a valid IPV4 address").toString());
            ipAddressBytes[count++] = ipAddressPart;
        }
        return ipAddressBytes;
    }

 

 

你可能感兴趣的:(java)