`

Linux上使用Java获取本机Ip地址的问题

阅读更多

可以用如下代码:

 

InetAddress inet = InetAddress.getLocalHost();
System.out.println("本机的ip=" + inet.getHostAddress());
 


在window下面可以工作。在Linux下返回127.0.0.1。主要是在linux下返回的是/etc/hosts中配置的localhost的ip地址,而不是网卡的绑定地址。后来改用网卡的绑定地址,可以取到本机的ip地址:)

代码如下:


//根据网卡取本机配置的IP
Enumeration netInterfaces=NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while(netInterfaces.hasMoreElements())
{
    NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement();
    System.out.println(ni.getName());
    ip=(InetAddress) ni.getInetAddresses().nextElement();
    if( !ip.isSiteLocalAddress()
            && !ip.isLoopbackAddress()
            && ip.getHostAddress().indexOf(":")==-1)
    {
        System.out.println("本机的ip=" + ip.getHostAddress());
        break;
    }
    else
    {
        ip=null;
    }
}
 
分享到:
评论
2 楼 wtslh 2009-11-20  
谢谢了,使用上
1 楼 wjason 2009-03-05  
从baidu搬过来的时候,
格式不好,
调整了一下~~
Global site tag (gtag.js) - Google Analytics