我用如下方法:
public static String getLocalIP() {
String ipAdress = "";
String myHost = "";
InetAddress myIPaddress = null;
try {
myIPaddress = InetAddress.getLocalHost();
myHost = myIPaddress.toString();
ipAdress = myHost.substring(myHost.indexOf("/") + 1, myHost
.length());// ip部分
} catch (UnknownHostException e) {
}
return (ipAdress);
}
在windows下可以得到真实ip,但是在linux下运行时,得到的却是127.0.0.1
如何才能在linux下得到真正的本机ip呢?请教各位!谢谢:)

解决方案 »

  1.   

    为什么不直接读取 eth-ifconfig文件?
      

  2.   

    linux下默认是有一个127.0.0.1的ip地址! ifconfig看看就知道了。
      

  3.   

    我的问题已经解决:),自己鼓个掌先!
    首先谢谢llhdf(塞外浪子) !解决过程如下:
    在出现问题后,查找到网上有关资料,别人是这样解决:
    java获取本机的ip地址-解决Linux下取得IP为127.0.0.1问题 可以用如下代码:           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;
           }
       }套用别人的代码,我的报错:空指针错误!抓头!!
      

  4.   

    继续研究,发现InetAddress.getHostAddress()其实是去读取etc/hosts下的配置文件,打开我的文件,发现我的hosts文件内容如下(因为是为了网络访问,所以有改过配置):
    # Do not remove the following line, or various programs
    # that require network functionality will fail.
    127.0.0.1 localhost.localdomain localhost
    XXX.XX.X.XXX test.com所以就对我的代码进行如下调整:
    public static String test() throws UnknownHostException{
    InetAddress all; 
    StringBuffer sb = new StringBuffer();
    all = InetAddress.getByName("test.com");
    //     all = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName()); 
        String s = all.getHostAddress();
        return s;
    }ok了!