ITPub博客

首页 > 应用开发 > Java > Linux下用Java获取本机IP地址

Linux下用Java获取本机IP地址

Java 作者:壹頁書 时间:2016-05-31 12:51:17 0 删除 编辑
转载自:
http://blog.sina.com.cn/s/blog_956a67ae010101tr.html

开始我在Linux下用InetAddress.getLocalHost()方法获取本机IP地址,
得到的结果总是:127.0.1.1。
原来这个是etc/hosts文件中的配置,并非网卡的IP地址。
后来多方寻访,终于得下以下代码,
运行后在控制台输出IP与MAC地址。

  1. import java.net.*;  
  2. import java.util.*;  
  3.   
  4. public class getIP {  
  5.    public static void main(String[] args) {  
  6.   
  7.    getIP t = new getIP();  
  8.    System.out.println(t.getLocalIP());  
  9.    System.out.println(t.getMacAddr());  
  10.    }  
  11.   
  12.    public String getMacAddr() {    
  13.        String MacAddr = "";  
  14.        String str = "";  
  15.        try {  
  16.            NetworkInterface NIC = NetworkInterface.getByName("eth0");  
  17.            byte[] buf = NIC.getHardwareAddress();  
  18.            for (int i = 0; i < buf.length; i++) {  
  19.                str = str + byteHEX(buf[i]);  
  20.            }  
  21.            MacAddr = str.toUpperCase();  
  22.        } catch (SocketException e) {  
  23.            e.printStackTrace();  
  24.            System.exit(-1);  
  25.        }  
  26.        return MacAddr;  
  27.    }  
  28.   
  29.    public String getLocalIP() {  
  30.        String ip = "";  
  31.        try {  
  32.            Enumeration<?> e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();  
  33.            while (e1.hasMoreElements()) {  
  34.                NetworkInterface ni = (NetworkInterface) e1.nextElement();  
  35.                if (!ni.getName().equals("eth0")) {  
  36.                    continue;  
  37.                } else {  
  38.                    Enumeration<?> e2 = ni.getInetAddresses();  
  39.                    while (e2.hasMoreElements()) {  
  40.                        InetAddress ia = (InetAddress) e2.nextElement();  
  41.                        if (ia instanceof Inet6Address)  
  42.                            continue;  
  43.                        ip = ia.getHostAddress();  
  44.                    }  
  45.                    break;  
  46.                }  
  47.            }  
  48.        } catch (SocketException e) {  
  49.            e.printStackTrace();  
  50.            System.exit(-1);  
  51.        }  
  52.        return ip;  
  53.    }  
  54.   
  55.   
  56.    public static String byteHEX(byte ib) {  
  57.        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a','b', 'c', 'd', 'e', 'f' };  
  58.        char[] ob = new char[2];  
  59.        ob[0] = Digit[(ib >>> 4) & 0X0F];  
  60.        ob[1] = Digit[ib & 0X0F];  
  61.        String s = new String(ob);  
  62.        return s;  
  63.    }  
  64. }  

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2109694/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Slf4j和Log4j 2
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339966