获取本机IP的方法

public static String[] getAllLocalIP() {

    String[] localServers = null;

    try {

        InetAddress addr = InetAddress.getLocalHost();

        String hostName = addr.getHostName().toString();

        // 获取本机ip

        InetAddress[] ipsAddr = InetAddress.getAllByName(hostName);

        localServers = new String[ipsAddr.length];

        for (int i = 0; i < ipsAddr.length; i++) {

            if (ipsAddr[i] != null) {

                localServers[i] = ipsAddr[i].getHostAddress().toString();

            }

        }

    } catch (Exception e) {

    }

    return localServers;

}

  

这种方法在Windows下是没问题的,但是在Linux下运行的时候很有可能会是127.0.0.1,修改host虽然可以解决,但并不是个明智之举。下面这种方法在Windows和Linux下都可以获得正确的IP:

/**

 * 取得本机IP(可能有多个网卡,Linux和Windows都适用)

 * 

 * @return List

 */

public static List getAllLocalIP() {

    List localServers = new ArrayList();

    try {

        Enumeration netInterfaces = NetworkInterface

                .getNetworkInterfaces();

        InetAddress ip = null;

        while (netInterfaces.hasMoreElements()) {

            NetworkInterface ni = netInterfaces.nextElement();

            Enumeration address = ni.getInetAddresses();

            while (address.hasMoreElements()) {

                ip = address.nextElement();

                if (!ip.isLoopbackAddress()

                        && ip

                                .getHostAddress()

                                .matches(

                                        "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)")) {

                    // System.out.println("非回环ip:    " +

                    // ip.getHostAddress());

                    localServers.add(ip.getHostAddress());

                }

            }

        }

    } catch (SocketException e) {

        e.printStackTrace();

    }


    return localServers;

}
 

你可能感兴趣的:(linux,windows)