Java-通过IP地址获得域名和主机名

昨天停电,今天补上!!

今天换个方式贴,总感觉之前那样不太好


如何通过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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值