Java获取本地服务器IP

Java获取本地服务器IP,我们最简单的写法:

[java]  view plain  copy
  1. import java.net.InetAddress;    
  2. public class CatchIp{  
  3.  public static void main(String[] args)  
  4.     {  
  5.         try  
  6.         {  
  7.             // 获取IP地址  
  8.             String ip = InetAddress.getLocalHost().getHostAddress();  
  9.          
  10.             System.out.println("IP地址:"+ip);  
  11.         }  
  12.         catch (Exception e)  
  13.         {  
  14.             System.out.println("异常:" + e);  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.     }  

但是这样有个问题,我们在windows系统,我们可以获取正确的IP

但是放在linux,可能是获取的IP地址为:127.0.0.1

而且在生产系统中,一台服务器可能有很多张网卡,这样获取ip比较麻烦,具体要了解生产系统服务器的IP地址我们可以参考这个网址:

http://blog.163.com/abkiss@126/blog/static/3259410020117493943770/?suggestedreading

代码如下:

[java]  view plain  copy
  1. /* 
  2.  * To change this template, choose Tools | Templates 
  3.  * and open the template in the editor. 
  4.  */  
  5. package org.lib.com;  
  6.   
  7. /** 
  8.  * 
  9.  * @author Administrator 
  10.  */  
  11. import java.io.BufferedReader;  
  12. import java.io.IOException;  
  13. import java.io.InputStreamReader;  
  14. import java.net.Inet6Address;  
  15. import java.net.InetAddress;  
  16. import java.net.NetworkInterface;  
  17. import java.net.SocketException;  
  18. import java.net.UnknownHostException;  
  19. import java.util.ArrayList;  
  20. import java.util.Enumeration;  
  21. import java.util.List;  
  22.        
  23. public class TestAddr {  
  24.        
  25.         /** 
  26.          * 获取本机所有IP 
  27.          */  
  28.     private static String[] getAllLocalHostIP() {  
  29.         List<String> res = new ArrayList<String>();  
  30.         Enumeration netInterfaces;  
  31.         try {  
  32.             netInterfaces = NetworkInterface.getNetworkInterfaces();  
  33.             InetAddress ip = null;  
  34.             while (netInterfaces.hasMoreElements()) {  
  35.                 NetworkInterface ni = (NetworkInterface) netInterfaces  
  36.                         .nextElement();  
  37.                 System.out.println("---Name---:" + ni.getName());  
  38.                 Enumeration nii = ni.getInetAddresses();  
  39.                 while (nii.hasMoreElements()) {  
  40.                     ip = (InetAddress) nii.nextElement();  
  41.                     if (ip.getHostAddress().indexOf(":") == -1) {  
  42.                         res.add(ip.getHostAddress());  
  43.                         System.out.println("本机的ip=" + ip.getHostAddress());  
  44.                     }  
  45.                 }  
  46.             }  
  47.         } catch (SocketException e) {  
  48.             e.printStackTrace();  
  49.             }  
  50.             return (String[]) res.toArray(new String[0]);  
  51.         }  
  52.     public static String getLocalIP() {  
  53.            String ip = "";  
  54.            try {  
  55.                    Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();  
  56.                    while (e1.hasMoreElements()) {  
  57.                        NetworkInterface ni = (NetworkInterface) e1.nextElement();  
  58.                         System.out.println ("getLocalIP--nic.getDisplayName ():" + ni.getDisplayName ());   
  59.                     System.out.println ("getLocalIP--nic.getName ():" + ni.getName ());  
  60.                        if (!ni.getName().equals("eth0")) {  
  61.                            continue;  
  62.                        } else {  
  63.                        Enumeration<?> e2 = ni.getInetAddresses();  
  64.                            while (e2.hasMoreElements()) {  
  65.                            InetAddress ia = (InetAddress) e2.nextElement();  
  66.                            if (ia instanceof Inet6Address)  
  67.                                continue;  
  68.                            ip = ia.getHostAddress();  
  69.                        }  
  70.                            break;  
  71.                        }  
  72.                    }  
  73.                } catch (SocketException e) {  
  74.                    e.printStackTrace();  
  75.                    System.exit(-1);  
  76.                }  
  77.                return ip;  
  78.            }  
  79.         public static String getWinLocalIP ()   
  80.             {   
  81.                 String ip = "";   
  82.                 try   
  83.                 {   
  84.                     Enumeration <?> e1 = (Enumeration <?>) NetworkInterface.getNetworkInterfaces ();   
  85.                     while (e1.hasMoreElements ())   
  86.                     {   
  87.                         NetworkInterface ni = (NetworkInterface) e1.nextElement ();  
  88.                         System.out.println ("getWinLocalIP--nic.getDisplayName ():" + ni.getDisplayName ());   
  89.                         System.out.println ("getWinLocalIP--nic.getName ():" + ni.getName ());  
  90.                         Enumeration <?> e2 = ni.getInetAddresses ();   
  91.                         while (e2.hasMoreElements ())   
  92.                         {   
  93.                             InetAddress ia = (InetAddress) e2.nextElement ();   
  94.                             ip = ia.getHostAddress ();   
  95.                     }   
  96.                     }   
  97.                 }   
  98.                 catch (SocketException e)   
  99.                 {   
  100.                     e.printStackTrace ();   
  101.                 System.exit (-1);   
  102.                 }   
  103.                 return ip;   
  104.             }  
  105.         /** 
  106.          * 获取本机所有物理地址 
  107.          * 
  108.          * @return 
  109.          */  
  110.         public static String getMacAddress() {  
  111.         String mac = "";  
  112.         String line = "";  
  113.    
  114.         String os = System.getProperty("os.name");  
  115.   
  116.        if (os != null && os.startsWith("Windows")) {  
  117.             try {  
  118.                     String command = "cmd.exe /c ipconfig /all";  
  119.                     Process p = Runtime.getRuntime().exec(command);  
  120.        
  121.                     BufferedReader br = new BufferedReader(new InputStreamReader(p  
  122.                             .getInputStream()));  
  123.        
  124.                     while ((line = br.readLine()) != null) {  
  125.                         if (line.indexOf("Physical Address") > 0) {  
  126.                             int index = line.indexOf(":") + 2;  
  127.        
  128.                             mac = line.substring(index);  
  129.        
  130.                             break;  
  131.                         }  
  132.                     }  
  133.        
  134.                     br.close();  
  135.        
  136.                 } catch (IOException e) {  
  137.                 }  
  138.             }  
  139.        
  140.             return mac;  
  141.         }  
  142.        
  143.         public String getMacAddress(String host) {  
  144.             String mac = "";  
  145.             StringBuffer sb = new StringBuffer();  
  146.        
  147.             try {  
  148.                 NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress  
  149.                         .getByName(host));  
  150.        
  151.                 // byte[] macs = ni.getHardwareAddress();  
  152.        
  153.                 // for (int i = 0; i < macs.length; i++) {  
  154.                 // mac = Integer.toHexString(macs[i] & 0xFF);  
  155.                 //  
  156.                 // if (mac.length() == 1) {  
  157.                 // mac = '0' + mac;  
  158.                 // }  
  159.                 //  
  160.                 // sb.append(mac + "-");  
  161.                 // }  
  162.        
  163.             } catch (SocketException e) {  
  164.                 e.printStackTrace();  
  165.             } catch (UnknownHostException e) {  
  166.                 e.printStackTrace();  
  167.             }  
  168.        
  169.             mac = sb.toString();  
  170.             mac = mac.substring(0, mac.length() - 1);  
  171.        
  172.             return mac;  
  173.     }  
  174.        
  175.         /** 
  176.          * @param args 
  177.          */  
  178.         public static void main(String[] args) {  
  179.             TestAddr.getAllLocalHostIP();  
  180.             System.out.println("LocalIP:"+TestAddr.getLocalIP());  
  181.             System.out.println("getWinLocalIP:"+TestAddr.getWinLocalIP());  
  182.             System.out.println(TestAddr.getMacAddress());  
  183.         }  
  184.        
  185.     }  
当然 ,我们要是想获取服务器的唯一信息,经常有个偷懒的做法,那就是获取服务器的hostname,即主机名,写法也比较统一简单:

[java]  view plain  copy
  1. import java.net.InetAddress;    
  2. public class CatchHostname{  
  3.  public static void main(String[] args)  
  4.     {  
  5.         try  
  6.         {  
  7.             // 获取计算机名  
  8.             String name = InetAddress.getLocalHost().getHostName();  
  9.             System.out.println("计算机名:"+name);  
  10.            
  11.         }  
  12.         catch (Exception e)  
  13.         {  
  14.             System.out.println("异常:" + e);  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.     }  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值