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的更多相关文章

  1. ICMP and InetAddress.isReachable()

    In Java it is only possible to work with two types of sockets: stream based ones (or TCP ones - java ...

  2. mysql general log日志

    注:应一直出现http://www.cnblogs.com/hwaggLee/p/6030765.html文章中的问题 故mysql general log日志.查看具体是什么命令导致的. 打开 ge ...

  3. java中Inetaddress类

    InetAddress类 InetAddress类用来封装我们前面讨论的数字式的IP地址和该地址的域名. 你通过一个IP主机名与这个类发生作用,IP主机名比它的IP地址用起来更简便更容易理解. Ine ...

  4. Atitit GRASP(General Responsibility Assignment Software Patterns),中文名称为“通用职责分配软件模式”

    Atitit GRASP(General Responsibility Assignment Software Patterns),中文名称为"通用职责分配软件模式" 1. GRA ...

  5. OpenCASCADE General Transformation

    OpenCASCADE General Transformation eryar@163.com Abstract. OpenCASCADE provides a general transforma ...

  6. RS-232, RS-422, RS-485 Serial Communication General Concepts(转载)

    前面转载的几篇文章重点介绍了UART及RS-232.在工控领域除了RS-232以外,常用的串行通信还有RS-485.本文转载的文章重点介绍了RS-232.RS-422和RS-485. Overview ...

  7. 地理信息系统 - ArcGIS - 高/低聚类分析工具(High/Low Clustering ---Getis-Ord General G)

    前段时间在学习空间统计相关的知识,于是把ArcGIS里Spatial Statistics工具箱里的工具好好研究了一遍,同时也整理了一些笔记上传分享.这一篇先聊一些基础概念,工具介绍篇随后上传. 空间 ...

  8. InetAddress类

    InetAddress类是Java对IP地址(包括IPv4和IPv6)的高层表示.大多数其他网络类都要用到这个类,包括Socket,ServerSocket,URL,DatagramSocket,Da ...

  9. java-collections.sort异常Comparison method violates its general contract!

    转载:http://www.tuicool.com/articles/MZreyuv 异常信息 java.lang.IllegalArgumentException: Comparison metho ...

随机推荐

  1. 迷你版 smarty --模板引擎和解析

    http://blog.ipodmp.com/archives/php-write-a-mini-smarty-template-engine/ 迷你版Smarty模板引擎目录结构如下: ① 要开发一 ...

  2. sonar-maven-plugin问题

    问题: jenkins本地构建时sonar报错 StackOverflow问题 [ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven ...

  3. HTML新元素

    <canvas> 标签定义图形,比如图表和其他图像.该标签基于 JavaScript 的绘图 API <audio> 定义音频内容 <video> 定义视频(vid ...

  4. gentoo下的wpa_supplicant无线网配置

    在linux使用wpa_supplicant获得无线网的最痛苦的是莫过于去配置wpa_supplicant.conf文件了(当然对于linux老手这不算什么), 但是可以用一种简便的方法直接输入命令行 ...

  5. Python 函数式编程学习

    描述:通过将函数作为参数,使得功能类似的函数实现可以整合到同一个函数. Before def getAdd(lst): result = 0 for item in lst: result += it ...

  6. Vim粘贴代码时缩进混乱

    Vim粘贴代码时缩进混乱 via 背景 在终端Vim中粘贴代码时,发现插入的代码会有多余的缩进,而且会逐行累加.原因是终端把粘贴的文本存入键盘缓存(Keyboard Buffer)中,Vim则把这些内 ...

  7. JAVA与编译语言及解释语言的关系

    转自JAVA结合了编译和解释执行的优点 编译型语言是一次性编译成机器码,脱离开发环境独立运行,所以运行效率较高,但是由于编译成的是特定平台上机器码,所以可移植性差. 编译型语言的典型代表有C.C++. ...

  8. 【HDU 3652】 B-number (数位DP)

    B-number Problem Description A wqb-number, or B-number for short, is a non-negative integer whose de ...

  9. android文字阴影效果设置

    <TextView android:id="@+id/tvText1" android:layout_width="wrap_content" andro ...

  10. C# 验证码识别基础方法及源码

    先说说写这个的背景 最近有朋友在搞一个东西,已经做的挺不错了,最后想再完美一点,于是乎就提议把这种验证码给K.O.了,于是乎就K.O.了这个验证码.达到单个图片识别时间小于200ms,500个样本人工 ...