[英]Creating InetAddress object in Java
我正在嘗試將由 IP 號或名稱指定的地址轉換為字符串(即localhost
或127.0.0.1
)為InetAdress對象。 沒有構造函數,而是返回InetAddress 的靜態方法。 所以如果我得到一個主機名那不是問題,但是如果我得到 IP 號呢? 有一種方法可以獲取byte[],但我不確定這對我有什么幫助。 所有其他方法獲取主機名。
您應該能夠使用getByName或getByAddress 。
主機名可以是機器名稱,例如“java.sun.com”,也可以是其 IP 地址的文本表示
InetAddress addr = InetAddress.getByName("127.0.0.1");
可以像這樣使用采用字節數組的方法:
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
來自 InetAddress 的 API
主機名可以是機器名稱,例如“java.sun.com”,也可以是其 IP 地址的文本表示。 如果提供了文字 IP 地址,則僅檢查地址格式的有效性。
ip = InetAddress.getByAddress(new byte[] {
(byte)192, (byte)168, (byte)0, (byte)102}
);
InetAddress.getByName 也適用於 IP 地址。
來自 JavaDoc
主機名可以是機器名稱,例如“java.sun.com”,也可以是其 IP 地址的文本表示。 如果提供了文字 IP 地址,則僅檢查地址格式的有效性。
api 相當容易使用。
// Lookup the dns, if the ip exists.
if (!ip.isEmpty()) {
InetAddress inetAddress = InetAddress.getByName(ip);
dns = inetAddress.getCanonicalHostName();
}
這是一個獲取任何網站IP地址的項目,它非常有用且易於制作。
import java.net.InetAddress;
import java.net.UnkownHostExceptiin;
public class Main{
public static void main(String[]args){
try{
InetAddress addr = InetAddresd.getByName("www.yahoo.com");
System.out.println(addr.getHostAddress());
}catch(UnknownHostException e){
e.printStrackTrace();
}
}
}
InetAddress 類可用於以 IPv4 和 IPv6 格式存儲 IP 地址。 您可以使用InetAddress.getByName()
或InetAddress.getByAddress()
方法將 IP 地址存儲到對象。
在以下代碼片段中,我使用InetAddress.getByName()
方法來存儲 IPv4 和 IPv6 地址。
InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");
您還可以使用InetAddress.getByAddress()
通過提供字節數組來創建對象。
InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
此外,您可以使用InetAddress.getLoopbackAddress()
獲取本地地址,使用InetAddress.getLocalHost()
獲取使用機器名稱注冊的地址。
InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>
注意 - 確保通過 try/catch 包圍您的代碼,因為InetAddress
方法返回java.net.UnknownHostException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.