外出旅行、冬季保暖得常备户外袜、速干袜、加厚袜子哦。

猛戳乐途驿站http://zhoupa1188.taobao.com抢购品牌男女式加厚户外袜子,coolmax、全棉、保暖、吸汗、速干、登山、徒步袜子。满10包邮


谢炜的cnblogs

CSDN上比较完整:http://hi.csdn.net/xiefeifeihu

导航

获取本机IP的方法

 

隐藏行号 复制代码 源代码
  1. public static String[] getAllLocalIP() {
    
  2.     String[] localServers = null;
    
  3.     try {
    
  4.         InetAddress addr = InetAddress.getLocalHost();
    
  5.         String hostName = addr.getHostName().toString();
    
  6.         // 获取本机ip
    
  7.         InetAddress[] ipsAddr = InetAddress.getAllByName(hostName);
    
  8.         localServers = new String[ipsAddr.length];
    
  9.         for (int i = 0; i < ipsAddr.length; i++) {
    
  10.             if (ipsAddr[i] != null) {
    
  11.                 localServers[i] = ipsAddr[i].getHostAddress().toString();
    
  12.             }
    
  13.         }
    
  14.     } catch (Exception e) {
    
  15.     }
    
  16.     return localServers;
    
  17. }
    

 

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

隐藏行号 复制代码 源代码
  1. /**
    
  2.  * 取得本机IP(可能有多个网卡,Linux和Windows都适用)
    
  3.  * 
    
  4.  * @return List
    
  5.  */
    
  6. public static List getAllLocalIP() {
    
  7.     List localServers = new ArrayList();
    
  8.     try {
    
  9.         Enumeration netInterfaces = NetworkInterface
    
  10.                 .getNetworkInterfaces();
    
  11.         InetAddress ip = null;
    
  12.         while (netInterfaces.hasMoreElements()) {
    
  13.             NetworkInterface ni = netInterfaces.nextElement();
    
  14.             Enumeration address = ni.getInetAddresses();
    
  15.             while (address.hasMoreElements()) {
    
  16.                 ip = address.nextElement();
    
  17.                 if (!ip.isLoopbackAddress()
    
  18.                         && ip
    
  19.                                 .getHostAddress()
    
  20.                                 .matches(
    
  21.                                         "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)")) {
    
  22.                     // System.out.println("非回环ip:    " +
    
  23.                     // ip.getHostAddress());
    
  24.                     localServers.add(ip.getHostAddress());
    
  25.                 }
    
  26.             }
    
  27.         }
    
  28.     } catch (SocketException e) {
    
  29.         e.printStackTrace();
    
  30.     }
    
  31.     return localServers;
    
  32. }
    

posted on 2009-11-08 12:39  飞飞狐  阅读(355)  评论(0编辑  收藏  举报

外出旅行、冬季保暖得常备户外袜、速干袜、加厚袜子哦。

猛戳乐途驿站http://zhoupa1188.taobao.com抢购品牌男女式加厚户外袜子,coolmax、全棉、保暖、吸汗、速干、登山、徒步袜子。满10包邮