zoukankan      html  css  js  c++  java
  • General: Know How to Use InetAddress

    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.org
    Canonical Host Name: www.javalobby.org
    Host Address: 64.69.35.190
    Calculated Host Address: 64.69.35.190
    Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: false
    Is Reachable in 2 seconds: true
    ===== Printing Info for: 'By-Name (Using IP as Host)' =====
    Host Name: www.javalobby.org
    Canonical Host Name: www.javalobby.org
    Host Address: 64.69.35.190
    Calculated Host Address: 64.69.35.190
    Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: false
    Is Reachable in 2 seconds: true
    ===== Printing Info for: 'By-IP: (64.69.35.190)' =====
    Host Name: www.javalobby.org
    Canonical Host Name: www.javalobby.org
    Host Address: 64.69.35.190
    Calculated Host Address: 64.69.35.190
    Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: false
    Is Reachable in 2 seconds: true
    ===== Printing Info for: 'Special Local Host' =====
    Host Name: COFFEE-BYTES-2
    Canonical Host Name: 192.168.1.101
    Host Address: 192.168.1.101
    Calculated Host Address: 192.168.1.101
    Is Any Local: false - Is Link Local: false - Is Loopback: false - Is Multicast: false - Is Site Local: true
    Is Reachable in 2 seconds: true
    ===== Printing Info for: 'Local Host By IP' =====
    Host Name: localhost
    Canonical Host Name: localhost
    Host Address: 127.0.0.1
    Calculated Host Address: 127.0.0.1
    Is Any Local: false - Is Link Local: false - Is Loopback: true - Is Multicast: false - Is Site Local: false
    Is Reachable in 2 seconds: true
    Until next time,
    
    R.J. Lorimer 
    Contributing Editor - rj -at- javalobby.org 
    Author              - http://www.coffee-bytes.com 
    Software Consultant - http://www.crosslogic.com
  • 相关阅读:
    poj1006 Biorhythms ——中国剩余定理入门题
    hoj12614 Dictionary ——拓扑排序找环&&比赛残留题
    2013年4月23日 雨
    zoj1586 QS Network ——最小生成树入门题_Prim算法
    hoj12616 Median Tree ——最小生成树入门题&&比赛残留题_Kruscal算法
    tset3
    testhtml
    Oracle SQLID 与 Hash_value 算法及转换
    Linux 脚本中生成日志 set x
    test wrod
  • 原文地址:https://www.cnblogs.com/ghgyj/p/4039358.html
Copyright © 2011-2022 走看看