码迷,mamicode.com
首页 > Web开发 > 详细

General: Know How to Use InetAddress

时间:2014-10-21 03:34:28      阅读:316      评论:0      收藏:0      [点我收藏+]

标签: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.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

 

General: Know How to Use InetAddress

标签:des   style   blog   http   color   io   os   ar   java   

原文地址:http://www.cnblogs.com/ghgyj/p/4039358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!