『壹』 java中InetAddress的getAddress和getHostAddress有什麼區別
getHostAddress為byte數組,getAddress是個String字元串。
所以,getAddress方便展示,getHostAddress方便作為數據進行處理。
『貳』 請教Java Socket高人一個InetAddress類型的具體用法的含義是什麼
public static InetAddress getLocalHost()
throws UnknownHostException
Returns the address of the local host. This is achieved by retrieving
the name of the host from the system, then resolving that name into
an InetAddress.
Note: The resolved address may be cached for a short period of time.
If there is a security manager, its
checkConnect method is called
with the local host name and -1
as its arguments to see if the operation is allowed.
If the operation is not allowed, an InetAddress representing
the loopback address is returned.
Returns:
the address of the local host.
Throws:
UnknownHostException - if the local host name could not
be resolved into an address.
錯誤的原因,把滑鼠移到紅線,會提示
『叄』 java 怎麼根據IP地址獲取主機名
//看看這個代碼如何。
importjava.net.InetAddress;
importjava.net.UnknownHostException;
importjava.util.Properties;
importjava.util.Set;
{
publicstaticvoidmain(String[]args){
InetAddressnetAddress=getInetAddress();
System.out.println("hostip:"+getHostIp(netAddress));
System.out.println("hostname:"+getHostName(netAddress));
Propertiesproperties=System.getProperties();
Set<String>set=properties.stringPropertyNames();//獲取java虛擬機和系統的信息。
for(Stringname:set){
System.out.println(name+":"+properties.getProperty(name));
}
}
(){
try{
returnInetAddress.getLocalHost();
}catch(UnknownHostExceptione){
System.out.println("unknownhost!");
}
returnnull;
}
publicstaticStringgetHostIp(InetAddressnetAddress){
if(null==netAddress){
returnnull;
}
Stringip=netAddress.getHostAddress();//gettheipaddress
returnip;
}
publicstaticStringgetHostName(InetAddressnetAddress){
if(null==netAddress){
returnnull;
}
Stringname=netAddress.getHostName();//getthehostaddress
returnname;
}
}
這個代碼簡單明了,就是調用現成的InetAddress類
『肆』 inetaddress inetsocketaddress socketaddressd三個是什麼關系
InetAddress是Java對IP地址的封裝,代表互聯網協議(IP)地址;
InetAddress對象的獲取只能通過靜態方法,比如根據主機名獲取主機的ip地址封裝對象:
InetAddress add=InetAddress.getByName("BOPZKQZ9SSY5ECY");
InetSocketAddress是SocketAddress的實現子類。
此類實現 IP 套接字地址(IP 地址 + 埠號),不依賴任何協議。
在使用Socket來連接伺服器時最簡單的方式就是直接使用IP和埠,但Socket類中的connect方法並未提供這種方式,而是使用SocketAddress類來向connect方法傳遞伺服器的IP和埠。
SocketAddress只是個抽象類,它除了有一個默認的構造方法外,其它的方法都是abstract的,因此,我們必須使用SocketAddress的子類來建立SocketAddress對象,也就是唯一的子類InetSocketAddress
關鍵就是InetSocketAddress不基於任何協議,一般用於socket編程中。表面看InetSocketAddress多了一個埠號,埠的作用:一台擁有IP地址的主機可以提供許多服務,比如Web服務、FTP服務、SMTP服務等,這些服務完全可以通過1個IP地址來實現。
那麼,主機是怎樣區分不同的網路服務呢?顯然不能只靠IP地址,因為IP 地址與網路服務的關系是一對多的關系。
實際上是通過「IP地址+埠號」來區分不同的服務的。