General: Know How to Use InetAddress

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   ar   java   

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<ipAddress.length; i++) {            if(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

 

General: Know How to Use InetAddress

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.