1. 程式人生 > >Java-通過IP地址獲得域名和主機名

Java-通過IP地址獲得域名和主機名

昨天停電,今天補上!!

今天換個方式貼,總感覺之前那樣不太好

如何通過IP地址獲得域名和主機名?

過程是這樣的

1.先將IP地址轉換為位元組陣列

2.通過InetAddress類的getByAddress()方法,獲得網路主機中具有指定IP地址的InetAddress物件

3.呼叫InetAddress物件的getCanonicalHostName()方法,獲得對應的域名

4.通過getHostName()方法,獲得主機名

以下是所有的屬性

<span style="white-space:pre">	</span>public static JLabel label_ip;
	public static JLabel label_domain;
	public static JLabel label_host;
	//三個文字域
	public static JTextField tf_ip;
	public static JTextField tf_domain;                                                 
	public static JTextField tf_host;
	//兩個按鈕
	public static JButton btn_ByIpGainDomain;
	public static JButton btn_exit;
	//
	public static JFrame fr;
	public static JPanel panel;


try {
							
						<span style="white-space:pre">	</span>String ip=tf_ip.getText();				//IP地址
							String[] ipStr=ip.split("[.]");			//IP地址轉換為字串陣列
							byte[] ipBytes=new byte[4];				//宣告儲存轉換後IP地址的位元組陣列
							for (int i = 0; i < 4; i++) {
								int m=Integer.parseInt(ipStr[i]);	//轉換為整數
								byte b=(byte)(m&0xff);				//轉換為位元組
								ipBytes[i]=b;
							}
							InetAddress inetAddr=InetAddress.getByAddress(ipBytes);	//建立InetAddress物件
							String canonical=inetAddr.getCanonicalHostName();		//獲取域名
							String host=inetAddr.getHostName();						//獲取主機名
							tf_domain.setText(canonical);                           //在文字框中顯示域名                                                                                                                                
							tf_host.setText(host);									//在文字框中顯示主機名
						} catch (Exception e2) {
							// TODO: handle exception
							e2.printStackTrace();
						}

這兩天一直在用InetAddress這個類

以下有一個部落格可以借鑑以下 http://www.cnblogs.com/hnrainll/archive/2012/01/09/2317515.html

最為重要的一句話是

<strong>InetAddress的例項物件包含以數字形式儲存的IP地址,同時還可能包含主機名(如果使用主機名來獲取InetAddress的例項,或者使用數字來構造,</strong>
<strong>並且啟用了反向主機名解析的功能)。InetAddress類提供了將主機名解析為IP地址(或反之)的方法。</strong>
<strong>(官方文件中也有類似的解釋)</strong>

  • Host Name Resolution

    Host name-to-IP address resolution is accomplished through the use of a combination of local machine configuration information and network naming services such as the Domain Name System (DNS) and Network Information Service(NIS). The particular naming services(s) being used is by default the local machine configured one. For any host name, its corresponding IP address is returned.

    Reverse name resolution means that for any IP address, the host associated with the IP address is returned.

    The InetAddress class provides methods to resolve host names to their IP addresses and vice versa. 

Translation

主機名解析

主機名到 IP 地址的解析 通過使用本地機器配置資訊和網路命名服務(如域名系統(Domain Name System,DNS)和網路資訊服務(Network Information Service,NIS))來實現。要使用的特定命名服務預設情況下是本地機器配置的那個。對於任何主機名稱,都返回其相應的 IP 地址。

反向名稱解析 意味著對於任何 IP 地址,都返回與 IP 地址關聯的主機。

InetAddress 類提供將主機名解析為其 IP 地址(或反之)的方法。



今天精力好,我們一起來好好學習一下這個IP

首先我們知道百度  (www.baidu.com)  眾所周知

1.www

全球資訊網(亦作“Web”、“WWW”、“'W3'”,英文全稱為“World Wide Web”),是一個由許多互相連結的超文字組成的系統,通過網際網路訪問。

這一句足夠了,超文字說白了,就是你現在所看到的網頁頁面文字

2.baidu

自己命明

3.com

以com為結尾的是頂級域名

www.baidu.com   整個稱之為域名,為什麼要有域名,很簡單為了方便人們記憶,誰願意天天去記IP地址。

而DNS解析 可以實現域名的解析從而得到對應的IP地址

好像有些扯遠了

我們所用的類InetAddress中

getHostName

public String getHostName()
獲取此 IP 地址的主機名。

如果此 InetAddress 是用主機名建立的,則記憶並返回主機名;否則,將執行反向名稱查詢並基於系統配置的名稱查詢服務返回結果。如果需要查詢名稱服務,則呼叫 getCanonicalHostName

如果有安全管理器,則首先使用主機名和 -1 作為引數來呼叫其 checkConnect 方法,以檢視是否允許該操作。如果不允許該操作,則其返回 IP 地址的文字表示形式。


這個說明了當我們NEW 了一個InetAddress類時,它會帶著主機名一起建立。

上面的CODE還用到了getByAddress()方法

getByAddress

根據提供的主機名和 IP 地址建立 InetAddress。不檢查名稱服務的地址有效性。

主機名可以是機器名(如 "java.sun.com"),也可以是其 IP 地址的文字表示形式。

也不在主機名上執行有效性檢查。

如果 addr 指定 IPv4 地址,則返回 Inet4Address 的例項;否則將返回 Inet6Address 的例項。

IPv4 地址 byte 陣列的長度必須為 4 個位元組,IPv6 byte 陣列的長度必須為 16 個位元組

引數:
host - 指定主機
addr - 網路位元組順序的原始 IP 地址
返回:
根據原始 IP 地址建立的 InetAddress 物件。
丟擲:
從以下版本開始:
1.4

引數 :addr -網路位元組順序的原始地址

返回:根據原始IP地址 建立的InetAddress物件

附上完整CODE

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;

import javax.naming.Context;
import javax.swing.*;
public class ByIpGainDomainFrame extends JFrame{
	GetLocalHostIpFrame getLocalHostIpFrame;
	//三個標籤
	public static JLabel label_ip;
	public static JLabel label_domain;
	public static JLabel label_host;
	//三個文字域
	public static JTextField tf_ip;
	public static JTextField tf_domain;                                                 
	public static JTextField tf_host;
	//兩個按鈕
	public static JButton btn_ByIpGainDomain;
	public static JButton btn_exit;
	//
	public static JFrame fr;
	public static JPanel panel;
	public static void main(String[] args){
		fr=new JFrame("By ip gain the domain and host!");
		panel=new  JPanel();
		label_domain=auto_Label(panel, label_domain,50,50,50,50,"域名:");
		label_host=auto_Label(panel, label_host, 50, 100, 50, 50, "主機名:");
		label_ip=auto_Label(panel, label_ip, 50, 150, 50, 50, "IP:");
		tf_domain=auto_TextField(panel, tf_domain, 100, 50, 200, 50,null);
		tf_host=auto_TextField(panel, tf_host, 100, 100, 200, 50, null);
		tf_ip=auto_TextField(panel, tf_ip, 100, 150, 200, 50, null);
		
		panel.setLayout(null);
		
		
		
		
		
		
		
		auto_Button(panel,btn_ByIpGainDomain, 50, 300, 150, 50,"獲取域名和主機名",1);
		auto_Button(panel,btn_exit, 250, 300, 100, 50,"退出系統",0);
		
		
		fr.add(panel);
		fr.setSize(500, 500);
		fr.setDefaultLookAndFeelDecorated(true);
		fr.setVisible(true);
	}
	
	public static JLabel auto_Label(JPanel jPanel,JLabel label,int x,int y,int length,int width,String str){
			label=new JLabel();
			label.setText(str);
			label.setBounds(x,y,length,width);
			jPanel.add(label);
			return label;
	}
	public static JTextField auto_TextField(JPanel jPanel,JTextField tf,int x,int y,int length,int width,String str){
			tf=new JTextField();
			tf.setText(str);
			tf.setBounds(x,y,length,width);
			jPanel.add(tf);
			return tf;
	}
	private static void auto_Button(JPanel jPanel,JButton btn,int x,int y,int length,int width,String str,int choose){
			btn=new JButton();
			System.out.print("\n"+x+" "+y+" "+length+" "+width+" ");
			btn.setText(str);
			btn.setBounds(x,y,length,width);
			jPanel.add(btn);
			switch (choose) {
			case 1:{
				btn.addActionListener(new ActionListener(){
					@Override
					public void actionPerformed(ActionEvent e) {
						try {
							
							String ip=tf_ip.getText();				//IP地址
							String[] ipStr=ip.split("[.]");			//IP地址轉換為字串陣列
							byte[] ipBytes=new byte[4];				//宣告儲存轉換後IP地址的位元組陣列
							for (int i = 0; i < 4; i++) {
								int m=Integer.parseInt(ipStr[i]);	//轉換為整數
								byte b=(byte)(m&0xff);				//轉換為位元組
								ipBytes[i]=b;
							}
							InetAddress inetAddr=InetAddress.getByAddress(ipBytes);	//建立InetAddress物件
							String canonical=inetAddr.getCanonicalHostName();		//獲取域名
							String host=inetAddr.getHostName();						//獲取主機名
							tf_domain.setText(canonical);                           //在文字框中顯示域名                                                                                                                                
							tf_host.setText(host);									//在文字框中顯示主機名
						} catch (Exception e2) {
							// TODO: handle exception
							e2.printStackTrace();
						}
						
					}
				});
			}
				break;

			default:{
				btn.addActionListener(new ActionListener(){
					@Override
					public void actionPerformed(ActionEvent e) {
						// TODO 自動生成的方法存根
						System.exit(0);
					}
				});
			}
				break;
			}
			
	}
	
	
}