博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
General: Know How to Use InetAddress
阅读量:6277 次
发布时间:2019-06-22

本文共 6156 字,大约阅读时间需要 20 分钟。

Modern applications often need the ability to learn information about hosts out on the network. One key class in this process for Java developers is the java.net.InetAddress . This class allows you to figure out various information about hosts, as well as discovering host information by different means.

InetAddress is a deceptively simple class to use, in that it provides a simple API for working with some very complex concepts. For instance, it provides a standard interface for discovering IPv4 IP addresses as well as IPv6 IP addresses. In addition, it distinguishes between multicast and unicast address types transparently. Finally, there are facilities built-in for determining if a host is reachable.

Here are some useful tidbits to understand:

 

  • If the internet address is IPv6, the returned object from the static methods of InetAddress will be an Inet6Address object. Likewise, if the address is IPv4, the returned object from the static methods will be an Inet4Address object.
  • The IP Address lookup can be by byte[] , in which case highest-order byte format is used - so for the ip address 127.0.0.1 , you would have the byte[] {127,0,0,1} .
  • Host name resolution is goverened by caching that can be controlled by some Java system properties - from the Javadoc:
    networkaddress.cache.ttl (default: -1) 
    Indicates the caching policy for successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the successful lookup. 
    A value of -1 indicates "cache forever". 
    networkaddress.cache.negative.ttl (default: 10) 
    Indicates the caching policy for un-successful name lookups from the name service. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups. 
    A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

 

Here is a little example class that shows some of the common techniques for using InetAddress to discover various information:

package org.javalobby.tnt.net; import java.net.InetAddress; public class InetAddressTest {     public static void main(String[] args) throws Exception {                // Get by host name        InetAddress javalobby = InetAddress.getByName("javalobby.org");        // Get by IP as host name        InetAddress byIpAsName = InetAddress.getByName("64.69.35.190");        // Get by IP as highest-order byte array        InetAddress byIp = InetAddress.getByAddress(new byte[] { 64, 69, 35, (byte)190});        // Get Local address        InetAddress local = InetAddress.getLocalHost();        // Get Local Address by Loopback IP        InetAddress localByIp = InetAddress.getByName("127.0.0.1");                printAddressInfo("By-Name (Javalobby.org)", javalobby);        printAddressInfo("By-Name (Using IP as Host)", byIpAsName);        printAddressInfo("By-IP: (64.69.35.190)", byIp);        printAddressInfo("Special Local Host", local);        printAddressInfo("Local Host By IP", localByIp);    }     private static void printAddressInfo(String name, InetAddress... hosts) throws Exception {        System.out.println("===== Printing Info for: '" + name + "' =====");        for(InetAddress host : hosts) {                        System.out.println("Host Name: " + host.getHostName());            System.out.println("Canonical Host Name: " + host.getCanonicalHostName());            System.out.println("Host Address: " + host.getHostAddress());            System.out.println("Calculated Host Address: " + getIpAsString(host));            System.out.print("Is Any Local: " + host.isAnyLocalAddress());            System.out.print(" - Is Link Local: " + host.isLinkLocalAddress());            System.out.print(" - Is Loopback: " + host.isLoopbackAddress());            System.out.print(" - Is Multicast: " + host.isMulticastAddress());            System.out.println(" - Is Site Local: " + host.isSiteLocalAddress());            System.out.println("Is Reachable in 2 seconds: " + host.isReachable(2000));        }    }    private static String getIpAsString(InetAddress address) {        byte[] ipAddress = address.getAddress();        StringBuffer str = new StringBuffer();        for(int i=0; i
0) str.append('.'); str.append(ipAddress[i] & 0xFF); } return str.toString(); }}

Here is an example output:

===== Printing Info for: 'By-Name (Javalobby.org)' =====Host Name: javalobby.orgCanonical Host Name: www.javalobby.orgHost Address: 64.69.35.190Calculated Host Address: 64.69.35.190Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: falseIs Reachable in 2 seconds: true===== Printing Info for: 'By-Name (Using IP as Host)' =====Host Name: www.javalobby.orgCanonical Host Name: www.javalobby.orgHost Address: 64.69.35.190Calculated Host Address: 64.69.35.190Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: falseIs Reachable in 2 seconds: true===== Printing Info for: 'By-IP: (64.69.35.190)' =====Host Name: www.javalobby.orgCanonical Host Name: www.javalobby.orgHost Address: 64.69.35.190Calculated Host Address: 64.69.35.190Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: falseIs Reachable in 2 seconds: true===== Printing Info for: 'Special Local Host' =====Host Name: COFFEE-BYTES-2Canonical Host Name: 192.168.1.101Host Address: 192.168.1.101Calculated Host Address: 192.168.1.101Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: trueIs Reachable in 2 seconds: true===== Printing Info for: 'Local Host By IP' =====Host Name: localhostCanonical Host Name: localhostHost Address: 127.0.0.1Calculated Host Address: 127.0.0.1Is Any Local: false - Is Link Local: false - Is Loopback: true - Is Multicast: false - Is Site Local: falseIs Reachable in 2 seconds: trueUntil next time,R.J. Lorimer Contributing Editor - rj -at- javalobby.org Author              - http://www.coffee-bytes.com Software Consultant - http://www.crosslogic.com

 

转载于:https://www.cnblogs.com/ghgyj/p/4039358.html

你可能感兴趣的文章
Yii用ajax实现无刷新检索更新CListView数据
查看>>
App 卸载记录
查看>>
南京大学周志华教授当选欧洲科学院外籍院士
查看>>
计算机网络与Internet应用
查看>>
Django 文件下载功能
查看>>
走红日本 阿里云如何能够赢得海外荣耀
查看>>
磁盘空间满引起的mysql启动失败:ERROR! MySQL server PID file could not be found!
查看>>
点播转码相关常见问题及排查方式
查看>>
[arm驱动]linux设备地址映射到用户空间
查看>>
弗洛伊德算法
查看>>
【算法之美】求解两个有序数组的中位数 — leetcode 4. Median of Two Sorted Arrays
查看>>
精度 Precision
查看>>
Android——4.2 - 3G移植之路之 APN (五)
查看>>
Linux_DHCP服务搭建
查看>>
[SilverLight]DataGrid实现批量输入(like Excel)(补充)
查看>>
秋式广告杀手:广告拦截原理与杀手组织
查看>>
翻译 | 摆脱浏览器限制的JavaScript
查看>>
闲扯下午引爆乌云社区“盗窃”乌云币事件
查看>>
02@在类的头文件中尽量少引入其他头文件
查看>>
JAVA IO BIO NIO AIO
查看>>