关于JAVA取本机ip的一些传说

来源:互联网 发布:主人属下知错认罚规矩 编辑:程序博客网 时间:2024/05/01 02:47

关于JAVA取本机ip的一些传说

参考:http://kaza.iteye.com/blog/169889
http://webcache.googleusercontent.com/search?q=cache:nX6WhHN0qVoJ:sw1982.iteye.com/blog/854892+isSiteLocalAddress&cd=1&hl=zh-CN&ct=clnk&gl=cn

1.获取windows下本机Ip地址方法

InetAddress.getLocalHost().getHostAddress()

2.获取Linux下本机Ip地址方法

用ifconfig看网卡:


这个时候就需要枚举多网卡判断了

Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();

然后结合IP4的地址段做区分,主要利用以下两个方法:

ip.isSiteLocalAddress() && !ip.isLoopbackAddress()

完整方法:
import java.net.InetAddress;import java.net.NetworkInterface;import java.net.UnknownHostException;import java.util.Enumeration;/** * User: hangyushen Date: 13-12-31 Time: 上午10:33 */public class MainApp {    public static void main(String args[]) throws UnknownHostException {        // windows下获取本机ip地址方法在linux系统下的输出        System.out.println("+++++++++++++++++++++" + InetAddress.getLocalHost().getHostAddress());        InetAddress ip = null;        Enumeration<NetworkInterface> netInterfaces = null;        try {            netInterfaces = NetworkInterface.getNetworkInterfaces();            while (netInterfaces.hasMoreElements()) {                NetworkInterface ni = netInterfaces.nextElement();                System.out.println("DisplayName:" + ni.getDisplayName());                System.out.println("Name:" + ni.getName());                Enumeration<InetAddress> ips = ni.getInetAddresses();                // 输出计算机中所有设备的ip                while (ips.hasMoreElements()) {                    System.out.println("IP:" + ips.nextElement().getHostAddress());                    ip = ips.nextElement();                    // 查找需要的本地ip                    if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1 ) {                        System.out.println("--------------------------" + ip.getHostAddress());                    }                }            }        } catch (Exception e) {            e.printStackTrace();        }    }}


输出结果:

+++++++++++++++++++++127.0.1.1DisplayName:wlan0Name:wlan0IP:fe80:0:0:0:e84:dcff:fea6:e52e%3--------------------------192.168.132.205DisplayName:eth0Name:eth0IP:fe80:0:0:0:f21f:afff:fe2a:3511%2--------------------------192.168.112.129DisplayName:loName:loIP:0:0:0:0:0:0:0:1%1



0 0
原创粉丝点击