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
时间: 2024-08-03 01:38:04

General: Know How to Use InetAddress的相关文章

InetAddress类

import java.net.InetAddress; import java.net.UnknownHostException; public class InetAddressDemo { public static void main(String args[])throws UnknownHostException{ // fun(); fun_1(); } public static void fun_1() throws UnknownHostException // 获取主机名I

【论文:麦克风阵列增强】Speech Enhancement Based on the General Transfer Function GSC and Postfiltering

作者:桂. 时间:2017-06-06  16:10:47 链接:http://www.cnblogs.com/xingshansi/p/6951494.html 原文链接:http://pan.baidu.com/s/1i51Kymp 未完待续 前言 这篇文章是TF-GSC的改进版.虽然TF-GSC对于方向性干扰的抑制效果不错,对于弥散噪声(diffuse noise,题外话:不同方向directional noise的均值,或者接近这种效果,可以理解为diffuse noise.)TF-GS

access violation at address General protection fault

https://en.wikipedia.org/wiki/General_protection_fault In memory errors, the faulting program accesses memory that it should not access. Examples include: Attempting to write to a read-only portion of memory Attempting to execute bytes in memory whic

General protection fault Exceptions in Linux/IA32 Systems

Computer Systems A Programmer's Perspective Second Edition Exception number Description Exception class0 Divide error Fault13 General protection fault Fault14 Page fault Fault18 Machine check Abort32–127 OS-de?ned exceptions Interrupt or trap128 (0x8

InetAddress问题

InetAddress的方法 当输入InetAddress.getByAddress(new byte[]{127.0.0.1})的时候不会报错, 但是ip的各段值是0-255,当new byte[]{118.244.0.1}的时候就会报错,byte的范围是-127~128之间 可以通过方法 进行获取InetAddress对象

InetAddress,UDP, TCP

package hanshi.net; import java.net.*; public class count { public static void main(String[] args)throws Exception { InetAddress ia = InetAddress.getLocalHost(); //获取本地的 print(ia.getHostAddress()); print(ia.getHostName()); InetAddress iad = InetAddre

迭代器适配器(二) general inserter的简单实现

general inserter允许用户在指定位置插入. 实现代码如下: 1 #ifndef ITERATOR_H 2 #define ITERATOR_H 3 #include <iterator> 4 5 //BackInsertIterator 6 template <typename Container> 7 class InsertIterator 8 { 9 public: 10 typedef typename Container::value_type value_

Windows7 general operation/cmd notes

最近,肥仔b自从看到肥仔使用Windows快捷键后便醉心于此,因此肥仔也特意新开随笔,摘录日常学习纪要,供bb学习 : ) In my opinion, general operation and command of windows can be split as these parts. There's no doubt that you can improve your efficiency of work if you work it well 1. Windows 微徽键 ### 窗口

类InetAddress

如果一个类没有构造方法:A:成员全部是静态的(Math,Arrays,Collections)B:单例设计模式(Runtime)C:类中有静态方法返回该类的对象(InetAddress) public static InetAddress getByName(String host);//根据计算机名或者IP地址的字符串表示得到IP地址对象 import java.net.InetAddress; import java.net.UnknownHostException; /* 如果一个类没有构