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 ...
随机推荐
- CSS3之简易的3D模型构建[原创开源]
CSS3之简易的3D模型构建[开源分享] 先上一张图(成果图):这个是使用 3D建模空间[源码之一] 制作出来的模型之一 当然这是一部分模型特写, 之前还制作过枪的3D模型等等. 感兴趣的朋友可以自己 ...
- 【转】PFILE和SPFILE介绍
原文:http://blog.sina.com.cn/s/blog_77bba23901017xcl.html 一.PFILE Pfile(Parameter File,参数文件)是基于文本格式的参数 ...
- win7 64位Apache http server+PHP配置
一.下载PHP 1.首先下载apache http server(我本来是想在官网下载,但是找半天也没找到,于是就在网上下了一个老版本的)我是在这个网址下载的:http://download.csdn ...
- sass进阶篇总结一
一.@if 指令: @if 指令是一个 SassScript,它可以根据条件来处理样式块,如果条件为 true 返回一个样式块,反之 false 返回另一个样式块.在 Sass 中除了 @if 之,还 ...
- php提取背景图片
preg_match_all('/background\s*-\s*+image\s*:\s*url\s*\("*([^"]*)"*\)/i', $content,$ma ...
- Mysql 与 php动态网站开发 入门教程
这个系列的教程由表单开始写,因为表单可以把数据库和web 之间的交互表现得很明显.提交表单 ,数据库记录注册信息. 本教程属于基础教程.大神请略过. 对于php和mysql之间的稳固性很 ...
- qt5 基础知识
QWidget wQLineEdit edit; edit.show(); //如果没有这句,编辑框edit将会显示在父窗口的左上角edit.setParent(&w); //以w为父窗口并显 ...
- iOS 推荐博客
著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处.作者:Franz Fang链接:http://www.zhihu.com/question/20264108/answer/3026 ...
- C语言程序设计做题笔记之C语言基础知识(上)
C语言是一种功能强大.简洁的计算机语言,通过它可以编写程序,指挥计算机完成指定的任务.我们可以利用C语言创建程序(即一组指令),并让计算机依指令行事.并且C是相当灵活的,用于执行计算机程序能完成的几乎 ...
- ACdream训练赛系列のJava专场
/* * this code is made by mhy12345 * Problem: 1669 * Verdict: Accepted * Submission Date: 2015-04-21 ...