ホスト名からIPアドレスを取得する

実際にやってみる
import java.net.*; class InetAddressDemo { public static void main(String args[]) { try { InetAddress ias[] = InetAddress.getAllByName(args[0]); for (int i = 0; i < ias.length; i++) { System.out.println(ias[i].getHostName()); System.out.println(ias[i].getHostAddress()); byte bytes[] = ias[i].getAddress(); for (int j = 0; j < bytes.length; j++) { if (j > 0) System.out.print("."); if (bytes[j] >= 0) System.out.print(bytes[j]); else System.out.print(bytes[j] + 256); } System.out.println(""); } } catch (Exception e) { e.printStackTrace(); } } }
実行結果1(google.comのIPアドレスを取得する)

実行結果2(microsoft.comのIPアドレスを取得する)

goole.comのIPアドレスおかしくね?って思ったかもしれませんが
これは32ビットのIPアドレス(IPv4)ではなく、128ビットのIPアドレス(IPv6)です。
詳しくは、こちらをご覧ください
メソッドの解説
getByName()
ホスト名は「java.sun.com」のようなマシン名か「206.26.48.100」のような IP アドレスのような文字列を引数にします。そして、このメソッドは指定したホストの IPアドレスを示す InetAddress(インスタンス) を返します
getAllByName()
getByName() メソッドと同様に引数はホスト名でもIPアドレスでもかまいません
ホスト名は複数のIPアドレスに関連づけられていることがあります。このメソッドは指定したホストのIPアドレスを示すInetAddress(インスタンス)を返します。上記の例で言う”google.com”は2つと”microsoft.com”にはたくさんのIPアドレスが関連付けられています。
InetAddressは、IPアドレスを含んだオブジェクトだよ
getAddress()
InetAddress(インスタンス) から IPアドレスをbyteの配列で取得する
getHostName()
InetAddress(インスタンス) から ホスト名をStingで取得する
getHostAddress()
InetAddress(インスタンス) から ホスト名をStringで取得する
URLのHTMLを取得する
import java.io.*; import java.net.*; class URLDemo { public static void main(String args[]) { try { // Obtain URL URL url = new URL(args[0]); // Obtain input stream InputStream is = url.openStream(); // Read and display data from URL byte buffer[] = new byte[1024]; int i; while ((i = is.read(buffer)) != -1) { System.out.write(buffer, 0, i); } } catch (Exception e) { e.printStackTrace(); } } }
実行結果

このサイトはこちらになります。
メソッドの解説
URLクラスのコンストラクター
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, String file) throws MalformedURLException
URL(String urlString) throws MalformedURLException
openStream()
InputStream() throws IOException
openStream()
String getFile() String getHost() int getPort()
String getProtocol()
getFile()
String getFile()
getHost()
String getHost()
getPort()
int getPort()
getProtocol()
String getProtocol()
詳しくはこちらを見てね!