| |
中国建设银行云南省保山地区分行 杨绍方
当我们准备建立一个web站点,就必须向域名登记机构申请一个internet域名,因此,我们通常希望了解自己准备使用的域名是否已经被注册,这时,可以简单地访问internic站点http://www.internic.net/whois.html,在"registry whois"输入框中输入需查询的域名,就可以得到我们需要的结果。本文介绍了如何使用java编程来实现这个过程。
一 原理 原理非常简单,域名的查询主要是基于rfc 954提供的whois协议。在上述过程中,我们实际上是访问了internic站点的whois服务器,该服务器从whois数据库中查询我们所需要的内容。 whois服务器是一个基于"查询/响应"的tcp事务服务器,它运行在sri-nic机器上(26.0.0.73或10.0.0.51),向用户提供internet范围内的目录服务。本地主机上的用户程序可以通过internet访问该服务器,其过程主要有下面三步: (1)在tcp服务端口43(十进制)连接sri-nic服务主机; (2)发送一个命令,以回车和换行(<crlf>)结尾; (3)接受相应命令的返回信息,一旦输出结束,服务器将关闭连接。 命令的格式非常简单。可以直接输入域名,例如,可以使用"sohu.com"查询"搜狐"网站的域名信息;也可以使用"help"得到详细的帮助信息。
二 java socket编程简述 在java中,使用socket类可以实现客户端的sockets,建立与服务器的网络连接。本文使用下面所示的socket类的构造器来创建一个流socket,并连接到主机"whois.internic.net"的端口43。 public socket(string host, int port, boolean stream) throws ioexception 其中,参数host为远程主机的主机名,port为远程主机的端口号,如果参数stream为true,则创建一个流socket,否则创建一个数据报socket。 如果创建socket时发生i/o错误,将抛掷一个ioexception 异常。 当创建了一个连接到远程主机的socket对象后,我们可以使用getinputstream()和getoutputstream()方法分别得到该socket对象的输入流和输出流,用于对该socket进行数据读写,为了使应用程序设计简单,这些方法返回的流通常使用java.io包中的实例对象来处理,例如:datainputstream和printwriter。 从socket读数据使用readline()方法,一次读取一行数据(字符串): public string readline() throws ioexception 向socket写数据使用print()方法: public void print(string s) 当完成socket通讯后,应该首先关闭datainputstream和printwriter对象,最后才关闭socket对象。
三 源程序 import java.net.*; import java.io.*;
public class whois { public final static int port = 43; public final static string hostname = "whois.internic.net";
public static void main(string[] args) { socket thesocket; datainputstream thewhoisstream; printstream ps;
//检查命令行参数 if (args.length <1) { system.out.println("/nusage: java whois <command>"); system.out.println("parameters:"); system.out.println( "/tcommand = one or more domain name, or other command."); system.out.println("example:"); system.out.println("/tjava whois sohu.com"); system.out.println("/tjava whois help");
system.exit(1); //退出 }
try { //在tcp服务端口43(十进制)连接sri-nic服务主机 thesocket = new socket(hostname, port, true); ps = new printstream(thesocket.getoutputstream()); //发送用户提供的一个或多个命令 for (int i = 0; i < args.length; i++) ps.print(args[i] + " "); //以回车和换行(<crlf>)结尾 ps.print("/r/n");
//接受相应命令的返回信息 thewhoisstream = new datainputstream(thesocket.getinputstream()); string s; while ((s = thewhoisstream.readline()) != null) { system.out.println(s); }
//关闭datainputstream和printwriter thewhoisstream.close(); ps.close(); //关闭socket thesocket.close(); } catch (ioexception e) { system.err.println(e); } } } whois.java利用jdk1.2编译通过,在windows 98/nt的命令行提示符运行的方法为: java whois < internet域名或命令> 例如,查询"搜狐"的internet域名信息可以: java whois sohu.com 得到详细的帮助可以: java whois help 您可以发现,屏幕输出的内容与使用浏览器访问http://www.internic.net/whois.html得到的内容完全一样。
|
|