java.net.InetAddress类的应用

本文介绍了Java中的InetAddress类,详细讲解了如何通过不同方法获取InetAddress实例,包括使用getByName和getAllByName等方法解析主机名到IP地址的过程及注意事项。

1. java.net.InetAddress类的使用

1.1. 简介

IP地址是IP使用的32位(IPv4)或者128位(IPv6)位无符号数字,它是传输层协议TCPUDP的基础。InetAddressJavaIP地址的封装,在java.net中有许多类都使用到了InetAddress,包括ServerSocketSocketDatagramSocket等等。

InetAddress的实例对象包含以数字形式保存的IP地址,同时还可能包含主机名(如果使用主机名来获取InetAddress的实例,或者使用数字来构造,并且启用了反向主机名解析的功能)。InetAddress类提供了将主机名解析为IP地址(或反之)的方法。

InetAddress对域名进行解析是使用本地机器配置或者网络命名服务(如域名系统(Domain Name SystemDNS)和网络信息服务(Network Information ServiceNIS))来实现。对于DNS来说,本地需要向DNS服务器发送查询的请求,然后服务器根据一系列的操作,返回对应的IP地址,为了提高效率,通常本地会缓存一些主机名与IP地址的映射,这样访问相同的地址,就不需要重复发送DNS请求了。在java.net.InetAddress类同样采用了这种策略。在默认情况下,会缓存一段有限时间的映射,对于主机名解析不成功的结果,会缓存非常短的时间(10秒)来提高性能。

 

1.2. InetAddress对象的获取

InetAddress的构造函数不是公开的(public),所以需要通过它提供的静态方法来获取,有以下的方法:

static InetAddress[] getAllByName(String host)

static InetAddress getByAddress(byte[] addr)

static InetAddress getByAddress(String host,byte[] addr)

static InetAddress getByName(String host)

static InetAddress getLocalHost()

在这些静态方法中,最为常用的应该是getByName(String host)方法,只需要传入目标主机的名字,InetAddress会尝试做连接DNS服务器,并且获取IP地址的操作。代码片段如下,注意我们假设以下的代码,都是默认导入了java.net中的包,在程序的开头加上import java.net.*,否则需要指定类的全名java.net.InetAddress

InetAddress address=InetAddress.getByName("www.baidu.com");

注意到这些方法可能会抛出的异常。如果安全管理器不允许访问DNS服务器或禁止网络连接,SecurityException会抛出,如果找不到对应主机的IP地址,或者发生其他网络I/O错误,这些方法会抛出UnknowHostException。所以需要写如下的代码:

try

{

    InetAddress address=InetAddress.getByName("www.baidu.com");

     System.out.println(address);

}

catch(UnknownHostException e)

{

     e.printStackTrace();

}

下面是一则完整的例子:

package org.dakiler.javanet.chapter1;

 

import java.net.InetAddress;

 

/**

* this example is used to show how to get InetAddress instance

* @author Dakiler

*/

public class Example1

{

    public static void main(String args[])throws Exception

     {

         InetAddress address=InetAddress.getByName("www.baidu.com");

         System.out.println(address);

         System.out.println("-----");

         InetAddress[] addresses=InetAddress.getAllByName("www.baidu.com");

        for(InetAddress addr:addresses)

         {

             System.out.println(addr);

         }

     }

}

运行结果如下:

www.baidu.com/119.75.213.61

-----

www.baidu.com/119.75.213.61

www.baidu.com/119.75.216.30

在这个例子中,我们使用到了getByName()以及getAllByName()两个方法,前者通过"www.baidu.com"来获取InetAddress的对象,并且输出到控制台。System.out.println(address); 默认调用了InetAddress.toString()方法,在结果中可以看到"www.baidu.com/119.75.213.61"的输出结果,其中119.75.213.61为百度网站的IP地址。

getAllByName()方法是根据主机名返回其可能的所有InetAddress对象,保存在一个数组中。在这个例子中,输出的结果中,www.baidu.com有两个ip地址分别为119.75.213.61以及119.75.216.30。

另外一个静态常用的静态方法是getLocalHost(),返回的是本地地址,如下例:

package org.dakiler.javanet.chapter1;

 

import java.net.InetAddress;

 

public class Example2

{

    public static void main(String args[])throws Exception

     {

         InetAddress address=InetAddress.getLocalHost();

         System.out.println(address);

     }

}

这个例子首先是根据InetAddress.getLocalHost()方法获取本地IP地址,然后通过System.out.println()打印出来,结果如下:

dakiler/192.168.1.102

- Checking internet connectivity - Checking update center connectivity - Failed to resolve host name mirrors.tools.huawei.com. Perhaps you need to configure HTTP proxy? - java.net.UnknownHostException: mirrors.tools.huawei.com at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at sun.net.NetworkClient.doConnect(NetworkClient.java:175) at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) at sun.net.www.http.HttpClient.<init>(HttpClient.java:242) at sun.net.www.http.HttpClient.New(HttpClient.java:339) at sun.net.www.http.HttpClient.New(HttpClient.java:357) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220) at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1056) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984) at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480) at hudson.model.UpdateCenter$UpdateCenterConfiguration.testConnection(UpdateCenter.java:1407) at hudson.model.UpdateCenter$UpdateCenterConfiguration.checkUpdateCenter(UpdateCenter.java:1190) at hudson.model.UpdateCenter$ConnectionCheckJob.run(UpdateCenter.java:1639) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:121) at java.lang.Thread.run(Thread.java:748)报错详解
最新发布
10-15
wayzim-system-integration | Exception in thread "main" java.lang.reflect.InvocationTargetException wayzim-system-integration | at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) wayzim-system-integration | at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) wayzim-system-integration | at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) wayzim-system-integration | at java.lang.reflect.Method.invoke(Method.java:498) wayzim-system-integration | at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:49) wayzim-system-integration | at org.springframework.boot.loader.Launcher.launch(Launcher.java:108) wayzim-system-integration | at org.springframework.boot.loader.Launcher.launch(Launcher.java:58) wayzim-system-integration | at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:65) wayzim-system-integration | Caused by: java.net.UnknownHostException: wcs: wcs: Name or service not known wayzim-system-integration | at java.net.InetAddress.getLocalHost(InetAddress.java:1525) wayzim-system-integration | at com.wayzim.integration.WayzimSystemIntegrationApplication.main(WayzimSystemIntegrationApplication.java:35) wayzim-system-integration | ... 8 more wayzim-system-integration | Caused by: java.net.UnknownHostException: wcs: Name or service not known wayzim-system-integration | at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) wayzim-system-integration | at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:929) wayzim-system-integration | at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1343) wayzim-system-integration | at java.net.InetAddress.getLocalHost(InetAddress.java:1520) wayzim-system-integration | ... 9 more
07-26
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值