[網絡編程]——InetAddress_InetSocketAddress

public class Inet01 {
	/**
	 * 沒有封裝端口
	 * @author Administrator
	 *
	 */
	/**
	 * @param args
	 * @throws UnknownHostException 
	 * @throws MalformedURLException 
	 */
	public static void main(String[] args) throws UnknownHostException{		
		//使用getLocalHost方法創建InetAddress對象
		InetAddress addr = InetAddress.getLocalHost();
		System.out.println(addr.getHostAddress());  //返回:192.168.1.100
		System.out.println(addr.getHostName());  //輸出計算機名
		//根據域名得到InetAddress對象
		addr = InetAddress.getByName("www.baidu.com"); 
		System.out.println(addr.getHostAddress());  //返回 163服務器的ip:61.135.253.15
		System.out.println(addr.getHostName());  //輸出:www.163.com	
		//根據ip得到InetAddress對象
		addr = InetAddress.getByName("61.135.253.15"); 
		System.out.println(addr.getHostAddress());  //返回 163服務器的ip:61.135.253.15
		System.out.println(addr.getHostName());  //輸出ip而不是域名。如果這個IP地 址不存在或DNS服務器不允許進行IP地址和域名的映射,getHostName方法就直接返回這個IP地址。
	}

}

/**
* 封裝端口:在InetAddress基礎上+端口
* @author Administrator
*
*/
public class InetSocketDemo01 {
	/**
	 * @param args
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException {
		InetSocketAddress  address = new InetSocketAddress("127.8.0.1",9999);
		//address = new InetSocketAddress(InetAddress.getByName("127.3.0.1"),9999);
		System.out.println(address.getHostName());
		System.out.println(address.getPort());
		InetAddress addr =address.getAddress();
		System.out.println(addr.getHostAddress());  //返回:地址
		System.out.println(addr.getHostName());  //輸出計算機名
		
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章