编写一个输出本地IP的方法,源码入下:
import java.net.*;public class TestIP
{
public static void main(String args[])
    {
InetAddress ia = null;
String s = null;

try
{
s = ia.getHostAddress();
}
catch(Exception e)
{

}
System.out.println(s);
}
}可输出结果是null.为什么?

解决方案 »

  1.   

    InetAddress ia =  InetAddress.getLocalHost();;
            String s = null;        try {
                s = ia.getHostAddress();
            } catch (Exception e) {        }
            System.out.println(s);
      

  2.   

    你的ia对象本身就是个空,不能从中获得IP地址的。
      

  3.   

    import java.net.InetAddress;
    import java.net.UnknownHostException;public class CSDN5
    {
    public static void main(String args[])
    {
    InetAddress ia = null;
    try {
    ia=InetAddress.getLocalHost();
    } catch (UnknownHostException e1) {
    e1.printStackTrace();
    }
    String s = null;try
    {
    s = ia.getHostAddress();
    }
    catch(Exception e)
    {}
    System.out.println(s);
    }
    }
      

  4.   

    只需要改一个地方:s = ia.getLocalHost().getHostAddress();
      

  5.   

    ia是null 的,当然是空了,怎么可能用null去调用它的方法呢