昨天停电,今天补上!!
今天换个方式贴,总感觉之前那样不太好
如何通过IP地址获得域名和主机名?
过程是这样的
1.先将IP地址转换为字节数组
2.通过InetAddress类的getByAddress()方法,获得网络主机中具有指定IP地址的InetAddress对象
3.调用InetAddress对象的getCanonicalHostName()方法,获得对应的域名
4.通过getHostName()方法,获得主机名
以下是所有的属性
<span style="white-space:pre"> </span>public static JLabel label_ip;
public static JLabel label_domain;
public static JLabel label_host;
//三个文本域
public static JTextField tf_ip;
public static JTextField tf_domain;
public static JTextField tf_host;
//两个按钮
public static JButton btn_ByIpGainDomain;
public static JButton btn_exit;
//
public static JFrame fr;
public static JPanel panel;
try {
<span style="white-space:pre"> </span>String ip=tf_ip.getText(); //IP地址
String[] ipStr=ip.split("[.]"); //IP地址转换为字符串数组
byte[] ipBytes=new byte[4]; //声明存储转换后IP地址的字节数组
for (int i = 0; i < 4; i++) {
int m=Integer.parseInt(ipStr[i]); //转换为整数
byte b=(byte)(m&0xff); //转换为字节
ipBytes[i]=b;
}
InetAddress inetAddr=InetAddress.getByAddress(ipBytes); //创建InetAddress对象
String canonical=inetAddr.getCanonicalHostName(); //获取域名
String host=inetAddr.getHostName(); //获取主机名
tf_domain.setText(canonical); //在文本框中显示域名
tf_host.setText(host); //在文本框中显示主机名
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
这两天一直在用InetAddress这个类
以下有一个博客可以借鉴以下 http://www.cnblogs.com/hnrainll/archive/2012/01/09/2317515.html
最为重要的一句话是
<strong>InetAddress的实例对象包含以数字形式保存的IP地址,同时还可能包含主机名(如果使用主机名来获取InetAddress的实例,或者使用数字来构造,</strong>
<strong>并且启用了反向主机名解析的功能)。InetAddress类提供了将主机名解析为IP地址(或反之)的方法。</strong>
<strong>(官方文档中也有类似的解释)</strong>