InetAddress 사용법 본문

Programming/Java

InetAddress 사용법

halatha 2011. 3. 31. 02:43
//	http://cafe.naver.com/javacircle/10682
import java.net.InetAddress;

public class TestInetAddress
{
	public static void main(final String[] args) throws Exception
	{
		//	Get by host name
		InetAddress	javalobby	=	InetAddress.getByName("javalobby.org");
		//	Get by IP as host name
		InetAddress	byIpAsName	=	InetAddress.getByName("64.69.35.190");
		//	Get by IP as highest-order byte array
		InetAddress	byIp	=	InetAddress.getByAddress(new byte[] { 64, 69, 35, (byte)190 });
		//	Get local address
		InetAddress	local	=	InetAddress.getLocalHost();
		//	Get local address by loopback IP
		InetAddress localByIp	=	InetAddress.getByName("127.0.0.1");

		printAddressInfo("By-name (javalobby.org)", javalobby);
		printAddressInfo("By-name (using IP as host)", byIpAsName);
		printAddressInfo("By-IP (64.69.35.190)", byIp);
		printAddressInfo("Special local host", local);
		printAddressInfo("Local host by IP", localByIp);
	}

	private static void printAddressInfo(String name, InetAddress host) throws Exception
	{
		System.out.println("====== Printing Info for: '" + name + "' =====");
		System.out.println("Host name: " + host.getHostName());
		System.out.println("Canonical host name: " + host.getCanonicalHostName());
		System.out.println("Host address: " + host.getHostAddress());
		System.out.println("Calculated host address: " + getIpAsString(host));
		System.out.println("Is any local: " + host.isAnyLocalAddress());
		System.out.println(" - Is link local: " + host.isLinkLocalAddress());
		System.out.println(" - Is loopback: " + host.isLoopbackAddress());
		System.out.println(" - Is multicast: " + host.isMulticastAddress());
		System.out.println(" - Is site local: " + host.isSiteLocalAddress());
		System.out.println(" - Is reachable in 2 seconds: " + host.isReachable(2000));
	}

	private static String getIpAsString(InetAddress address)
	{
		byte[]	ipAddress	=	address.getAddress();
		StringBuffer	str	=	new StringBuffer();
		for ( int i = 0; i < ipAddress.length; ++i )
		{
			if ( 0 < i )	str.append('.');
			str.append(ipAddress[i] & 0xFF);
		}
		return	str.toString();
	}
}


Comments