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

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


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.1
DisplayName:wlan0
Name:wlan0
IP:fe80:0:0:0:e84:dcff:fea6:e52e%3
--------------------------192.168.132.205
DisplayName:eth0
Name:eth0
IP:fe80:0:0:0:f21f:afff:fe2a:3511%2
--------------------------192.168.112.129
DisplayName:lo
Name:lo
IP:0:0:0:0:0:0:0:1%1



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值