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 anInet6Address
object. Likewise, if the address is IPv4, the returned object from the static methods will be anInet4Address
object. - The IP Address lookup can be by
byte[]
, in which case highest-order byte format is used - so for the ip address127.0.0.1
, you would have thebyte[]
{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的更多相关文章
- ICMP and InetAddress.isReachable()
In Java it is only possible to work with two types of sockets: stream based ones (or TCP ones - java ...
- mysql general log日志
注:应一直出现http://www.cnblogs.com/hwaggLee/p/6030765.html文章中的问题 故mysql general log日志.查看具体是什么命令导致的. 打开 ge ...
- java中Inetaddress类
InetAddress类 InetAddress类用来封装我们前面讨论的数字式的IP地址和该地址的域名. 你通过一个IP主机名与这个类发生作用,IP主机名比它的IP地址用起来更简便更容易理解. Ine ...
- Atitit GRASP(General Responsibility Assignment Software Patterns),中文名称为“通用职责分配软件模式”
Atitit GRASP(General Responsibility Assignment Software Patterns),中文名称为"通用职责分配软件模式" 1. GRA ...
- OpenCASCADE General Transformation
OpenCASCADE General Transformation eryar@163.com Abstract. OpenCASCADE provides a general transforma ...
- RS-232, RS-422, RS-485 Serial Communication General Concepts(转载)
前面转载的几篇文章重点介绍了UART及RS-232.在工控领域除了RS-232以外,常用的串行通信还有RS-485.本文转载的文章重点介绍了RS-232.RS-422和RS-485. Overview ...
- 地理信息系统 - ArcGIS - 高/低聚类分析工具(High/Low Clustering ---Getis-Ord General G)
前段时间在学习空间统计相关的知识,于是把ArcGIS里Spatial Statistics工具箱里的工具好好研究了一遍,同时也整理了一些笔记上传分享.这一篇先聊一些基础概念,工具介绍篇随后上传. 空间 ...
- InetAddress类
InetAddress类是Java对IP地址(包括IPv4和IPv6)的高层表示.大多数其他网络类都要用到这个类,包括Socket,ServerSocket,URL,DatagramSocket,Da ...
- java-collections.sort异常Comparison method violates its general contract!
转载:http://www.tuicool.com/articles/MZreyuv 异常信息 java.lang.IllegalArgumentException: Comparison metho ...
随机推荐
- tomcat配置虚拟目录的步骤
1.在tomcat中.....\conf\Catalina\localhost中创建一个test.xml文件 2.然后在\conf的server.xml中的 <Host > 元素里面 添加 ...
- Pyhon编码事项
1. 永远不要使用import * Pylint代码审查:Wildcard import XXX 如果函数名重名,或者要导入的内容里面包含了from datetime import datetime, ...
- 导航 -MapKit - 获取路线信息绘制导航路线
#import "PPViewController.h" #import <MapKit/MapKit.h> #import "PPAnnotation.h& ...
- 《Linux命令行大全》系列(二、导航)
文件系统的导航,是一个不断访问树形结构中节点的过程. 文件系统树 Linux只有一个倒立的文件系统树 不同设备可以挂载到这同一个树上 文件和子目录是此树的组成部分,最顶层的即根目录 目录 根据树节点间 ...
- BZOJ 1715: [Usaco2006 Dec]Wormholes 虫洞
Description John在他的农场中闲逛时发现了许多虫洞.虫洞可以看作一条十分奇特的有向边,并可以使你返回到过去的一个时刻(相对你进入虫洞之前).John的每个农场有M条小路(无向边)连接着N ...
- Dirichlet Process 和 Dirichlet Process Mixture模型
Dirichlet Process 和 Dirichlet Process Mixture模型 [本文链接:http://www.cnblogs.com/breezedeus/archive/2012 ...
- EasyUI 树形菜单tree 定义图标
{ "id":1, "text":"Folder1", "iconCls":"icon-save", ...
- http://www.cnblogs.com/xdp-gacl/p/3951952.html
http://www.cnblogs.com/xdp-gacl/p/3951952.html http://www.cnblogs.com/kristain/articles/2409021.html
- SPRING IN ACTION 第4版笔记-第二章-001-用@Autowired\@ComponentScan、@Configuration、@Component实现自动装载bean
1. package soundsystem; import org.springframework.context.annotation.ComponentScan; import org.spri ...
- Https协议:SSL建立过程分析(也比较清楚,而且有OpenSSL的代码)
web访问的两种方式: http协议,我们一般情况下是通过它访问web,因为它不要求太多的安全机制,使用起来也简单,很多web站点也只支持这种方式下的访问. https协议(Hypertext Tra ...