InetAddress类内部隐藏了地址数字。
工厂方法:
InetAddress类明显的构造方法。为生成一个InetAddress对象,必须运用一个可用的工厂方法
工厂方法(facroty method)仅是一个类中静态方法返回一个该类实例的约定。对于InetAddress,三个方法getLocalHost(), getByName()以及getAllByName()可以用来创建InetAddress的实例。
package com.ifeng.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPDemo
{
public static void main(String[] args)
{
try
{
InetAddress net = InetAddress.getLocalHost();
System.out.println(net.toString());
System.out.println("Address: "+net.getHostAddress());
System.out.println("Name: "+net.getHostName());
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress inet = null;
try
{
inet = InetAddress.getByName("www.baidu.com");
System.out.println("Address:"+inet.getHostAddress());
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}