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 ...
随机推荐
- PHP实现斐波那契数列非递归方法
斐波那契数列,又称黄金分割数列,指的是这样一个数列:0.1.1.2.3.5.8.13.21.……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n ...
- WPF中的字体改善
WPF4对字体渲染做了很大的改善,增加了TextOptions属性,该属性可以设置TextFormattingMode,TextRenderingMode,TextHintingMode 1.Text ...
- 安装Oracle 11gR2,报错:[INS-06101] IP address of localhost could not be determined
安装Oracle 11gR2,报错:[INS-06101] IP address of localhost could not be determined 出现这种错误是因为主机名和/etc/host ...
- silverlight5开发的翻牌游戏
扑克牌用了一个自定义控件,代码如下 public class CardButton : Button { public int state;//是否翻转0是未翻转,1是已翻转 private stat ...
- 菜鸟Android之路(上)
自己为什么要学android 本人作为应届毕业生,自己进入社会前做过好多梦,可是呢,现实还是打败了无邪!!面对社会的压力和残酷的竞争力自己如何生成下去??我自己对自己说:第一步 先养活自己,才能走好以 ...
- bzoj 1200: [HNOI2005]木梳 DP
1200: [HNOI2005]木梳 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 266 Solved: 125[Submit][Status] ...
- hdu 4749
题目很简单,不过题意很难看懂. 就是给一个标准的大小关系的队列,从原队列中找出最多的匹配子队列,感觉就像一个KMP算法+贪心: 不过这个题可能数据有点水把,竟然只要判断相邻的关系就可以A掉: 代码: ...
- 最简单的CRC32源码-查表法
这个算法是在逐BYTE法的基础上进行修改的,在上一篇文章里我们说过,如果不查表的话,逐BYTE法和逐BIT法没什么区别,现在我们就把这个算法写出来,注意在调用CRC校验函数前需要先调用表生成函数: u ...
- ASP.NET MVC 解决LINQ表达式中的SqlMethods 未找到命名空间问题
右键项目属性下的引用: 添加引用: 搜索寻找——System.Data.Linq,然后添加成功,即可解决LINQ表达式中的SqlMethods 未找到命名空间问题
- android:layout_weight详解
参考; www.cnblogs.com/alpha-bowen/archive/2011/03/02/1969343.html 总结: 当需要对页面按比例分配时会用到这个选项: layout_weig ...