java.net
類 InetAddress 此類表示互聯網協議 (IP) 地址。 會拋出異常 UnknownHostException
直接已知子類:
Inet4Address, Inet6Address
沒有構造函數,但是可以通過靜態方法獲取對象后,在完成其它功能的使用。
例如:
1
2
3
4
5
6
|
static InetAddress getLocalHost() 返回本地主機。 static InetAddress getByName(String host) 在給定主機名的情況下確定主機的 IP 地址。 static InetAddress[] getAllByName(String host) 在給定主機名的情況下,根據系統上配置的名稱服務返回其 IP 地址所組成的數組。 String getHostAddress() 返回 IP 地址字符串(以文本表現形式)。 String getHostName() 獲取此 IP 地址的主機名 String getCanonicalHostName() 獲取此 IP 地址的完全限定域名。即將主機名解析為IP地址 |
例子1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import java.net.*; class IPDemo { public static void main(String[] args) throws Exception { // InetAddress localhost = InetAddress.getLocalHost(); // System.out.println("localhost="+localhost); //返回本地主機(主機名和IP地址) // String hostname = localhost.getHostName(); //返回本地主機中的主機名 // String hostIP = localhost.getHostAddress(); //返回本地主機中的IP地址 // System.out.println("hostname="+hostname+"\n"+"hostIP="+hostIP); //InetAddress ia = InetAddress.getByName("www.baidu.com"); //System.out.println("name="+ia.getHostName()); //System.out.println("adress="+ia.getHostAddress()); InetAddress[] iad = InetAddress.getAllByName( "www.baidu.com" ); //百度提供的不止一個主機 for ( int i= 0 ;i<iad.length;i++) { System.out.println( "name=" +iad[i].getHostName()); System.out.println( "adress=" +iad[i].getHostAddress()); } } } |
1
2
3
4
5
6
7
|
import java.net.*; String getFile() 獲取此 URL 的文件名。 String getHost() 獲取此 URL 的主機名(如果適用)。 String getPath() 獲取此 URL 的路徑部分。 int getPort() 獲取此 URL 的端口號。 String getProtocol() 獲取此 URL 的協議名稱。 String getQuery() 獲取此 URL 的查詢部分。 |
例子2:URL使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class URLDemo { public static void main(String[] args) throws Exception { URL url = new URL( "http://192.168.1.105:8080/myweb/demo.html?name=haha&age=20" ); System.out.println( "getProtocol() :" +url.getProtocol()); System.out.println( "getHost() :" +url.getHost()); System.out.println( "getPort() :" +url.getPort()); System.out.println( "getFile() :" +url.getFile()); System.out.println( "getPath() :" +url.getPath()); System.out.println( "getQuery() :" +url.getQuery()); } } |
例子3:URLConnection連接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import java.io.*; import java.net.*; class URLConnectionDemo { public static void main(String[] args) throws Exception { URL url = new URL( "http://192.168.1.105:8080/myweb/demo.html" ); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); byte [] buf = new byte [ 1024 ]; int len = in.read(buf); System.out.println( new String(buf, 0 ,len)); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!