1、InetAddress類實現簡單IP掃描獲得主機名
- package demo.net;
-
- import java.net.InetAddress;
- import java.net.UnknownHostException;
-
- /*
- * 獲取指定IP的主機名
- */
- public class IPScanner {
-
- // 傳入IP地址,返回主機名稱,若主機不可達則返回ip地址的字符串形式
- public static String scanner(byte[] ip) {
- InetAddress addr = null;
- try {
- addr = InetAddress.getByAddress(ip);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- return addr.getHostName();
- }
-
- public static void main(String[] args) {
- String hostName;
- String ip;
- for (int i = 0; i <= 127; i++) {
- ip = "59.68.255." + i;
- hostName = scanner(new byte[] { 59, 68, (byte) 255, (byte)i });
- if (!ip.equals(hostName))
- System.out.println(ip +" : "+hostName);
- }
- }
- }
2、URL示例
- package demo.net;
-
- import java.io.IOException;
- import java.net.URL;
- import java.util.Scanner;
-
- /*
- * URL類用法示例,URL是統一資源定位符,可以打開到達一個資源的流,從而獲取資源的內容
- * 示例中獲取Linux公社首頁的內容,返回的內容是html文本
- */
- public class URLDemo {
- public static void main(String[] args) {
- try {
- URL url = new URL(http://www.linuxidc.com);
- Scanner in = new Scanner(url.openStream());
- while (in.hasNextLine())
- System.out.println(in.nextLine());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
運行結果:輸出html頁面源碼