IP 주소 및 도메인 이름 가져오기

2116 단어 java.netInetAddress
IP 주소 및 도메인 이름 가져오기

package com.itheima.net;

import java.net.InetAddress;

public class TextGetIPAndDomain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		getLocalIP();
		String hostName="www.sohu.com";
		getIPByName(hostName);
		getAllIPByName(hostName);
		
	}
	//     IP
	public static void getLocalIP(){
		try {
			InetAddress addr=InetAddress.getLocalHost();//      IP  
			String hostAddr=addr.getHostAddress();  //  IP   
			String hostName=addr.getHostName();  //       
			System.out.println("  IP  :"+hostAddr);
			System.out.println("     :"+hostName);
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("      IP  :"+e.getMessage());
			System.exit(1);
		}
		
	}
	
	//         IP  
	public static void getIPByName(String hostName){
		InetAddress addr;
		try {
			addr=InetAddress.getByName(hostName); //          
			String hostAddr=addr.getHostAddress(); //     Ip  
			System.out.println("   :"+hostName+"   IP  :"+hostAddr);
		} catch (Exception e) {
			System.out.println("          IP  :"+e.getMessage());
			System.exit(1);
		}
	}
	
	//           Ip
	public static void getAllIPByName(String hostName){
		InetAddress[] addrs;
		try {
			addrs=InetAddress.getAllByName(hostName);  //            
			String [] ips=new String[addrs.length];
			System.out.println("   :"+hostName+"      IP   :");
			for (int i = 0; i < addrs.length; i++) {
				ips[i]=addrs[i].getHostAddress(); //     IP  
				System.out.println(ips[i]);
			}
			
		} catch (Exception e) {
			System.out.println("             IP  :"+e.getMessage());
			System.exit(1);
			
		}
	}

}

좋은 웹페이지 즐겨찾기