host name 얻기 본문

Programming/Java

host name 얻기

halatha 2011. 3. 31. 02:31
import java.net.InetAddress;
import java.net.UnknownHostException;

class GetHostName
{
	public static void main(final String[] args)
	{
		//	http://www.devx.com/tips/Tip/13284:
		try {
			java.net.InetAddress localMachine =
				java.net.InetAddress.getLocalHost();
			System.out.println("Hostname of local machine: " +
					localMachine.getHostName());
		}
		catch (java.net.UnknownHostException uhe) { // [beware typo in code sample -dmw]
			// handle exception
		}

		//	http://javaalmanac.com/egs/java.net/GetHostname.html:
		try {
			// Get hostname by textual representation of IP address
			InetAddress addr = InetAddress.getByName("127.0.0.1"); // [127.0.0.1 is always localhost -dmw]/

			// Get hostname by a byte array containing the IP address
			byte[] ipAddr = new byte[]{127, 0, 0, 1};
			addr = InetAddress.getByAddress(ipAddr);

			// Get the host name from the address
			String hostname = addr.getHostName();

			// Get canonical host name
			String hostnameCanonical = addr.getCanonicalHostName();
		}
		catch (UnknownHostException e) {
			// handle exception
		}
	}
}

Comments