はじめに
Runtimeで外部アプリを叩いているだけじゃないか、というご指摘はごもっともです。
事前に以下のアプリケーションをインストールします。
・jwhois
Linux版のみ(かと..)
https://www.gnu.org/software/jwhois/
インストール例
$ yum install jwhois
$ yum install bind-utils
実装例
サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。
結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。
Whois.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
*
* @author tool-taro.com
*/
public class Whois {
public static void main(String[] args) throws IOException, InterruptedException {
//検索したいドメイン・IPアドレス
String source = "tool-taro.com";
//JWhoisのパス
String jwhoisPath = "/usr/bin/whois";
//Whois処理
String[] commandArray = new String[2];
commandArray[0] = jwhoisPath;
commandArray[1] = source;
String tempEncoding = "UTF-8";
//IPアドレスの場合はISO-2022-JPで返却されることが多い
try {
Integer.parseInt(source.replace(".", ""));
tempEncoding = "ISO-2022-JP";
}
catch (NumberFormatException e) {
}
final String encoding = tempEncoding;
Runtime runtime = Runtime.getRuntime();
Process process = null;
StringBuilder logBuilder = new StringBuilder();
StringBuilder errorBuilder = new StringBuilder();
int status = 0;
try {
process = runtime.exec(commandArray);
final InputStream in = process.getInputStream();
final InputStream ein = process.getErrorStream();
Runnable inputStreamThread = () -> {
BufferedReader reader = null;
String line;
try {
reader = new BufferedReader(new InputStreamReader(in, encoding));
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
logBuilder.append(line).append("\n");
}
}
catch (Exception e) {
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (Exception e) {
}
}
}
};
Runnable errorStreamThread = () -> {
BufferedReader reader = null;
String line;
try {
reader = new BufferedReader(new InputStreamReader(ein, encoding));
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
errorBuilder.append(line).append("\n");
}
}
catch (Exception e) {
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (Exception e) {
}
}
}
};
Thread inThread = new Thread(inputStreamThread);
Thread errorThread = new Thread(errorStreamThread);
inThread.start();
errorThread.start();
status = process.waitFor();
inThread.join();
errorThread.join();
}
finally {
if (process != null) {
try {
process.destroy();
}
catch (Exception e) {
}
}
}
//標準出力
System.out.format("検索結果=%1$s", logBuilder.toString());
}
}
動作確認
$ javac Whois.java
$ java Whois
$ 検索結果=[Querying whois.verisign-grs.com]
[Redirected to whois.discount-domain.com]
[Querying whois.discount-domain.com]
[whois.discount-domain.com]
Domain Name: tool-taro.com
...(省略)
環境
-
開発
- Windows 10 Pro
- JDK 1.8.0_112
- NetBeans IDE 8.2
-
動作検証
- CentOS Linux release 7.2
- JDK 1.8.0_112
上記の実装をベースにWebツールも公開しています。
Whois情報検索(ドメイン/IPアドレスサーチ)|Web便利ツール@ツールタロウ