InetAddress类中的getAddress()方法的返回值为什么直接是null?
问题描述:
正在学习java的socket编程。在看源码时候发现,InetAddress类中的getAddress()方法的返回值为null;
表示很蒙圈,望大神能解答
答
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println("this is address:" + address);
String hostName = address.getHostName();
String hostAddress = address.getHostAddress();
System.out.println("this is host name:" + hostName);
System.out.println("this is host address:" + hostAddress);
byte[] address4Byte = address.getAddress();
System.out.println("this is address4Byte len:" + address4Byte.length);
for (int i = 0; i < address4Byte.length; i++) {
System.out.print(address4Byte[i]);
}
}
这是楼主写的测试方法。我用byte[] address4Byte指向了address.getAddress();这个方法,但是address.getAddress();返回值是null;
但还是能获取到我的主机地址,这是为什么呢?
答
import java.net.InetAddress;
import java.net.UnknownHostException;
public class AA {
/**
* @param args
*/
public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("this is address:" + address);
String hostName = address.getHostName();
String hostAddress = address.getHostAddress();
System.out.println("this is host name:" + hostName);
System.out.println("this is host address:" + hostAddress);
byte[] address4Byte = address.getAddress();
System.out.println("this is address4Byte len:" + address4Byte.length);
for (int i = 0; i < address4Byte.length; i++) {
System.out.print(address4Byte[i]);
}
}
}
我运行没有错误的