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 ...
随机推荐
- js生成随机字符串或者随机数
//返回一个指定范围内的随机数 function createRandomNum(Min,Max){ let Range = Max - Min; let Rand = Math.random(); ...
- 简易ORM(基于注解)
这是从我们现有项目做的一定的改进准备做成IDE插件 类似getter和setter的生成 1.定义实体类 通过注解说明其表名和字段名(SOURCE类型的注解 不需要运行时使用)@TableName(& ...
- mysql自动备份数据库
可以选择设置需要备份的库,自动备份压缩,自动删除 7 天前的备份,需要使用 crontab 定时执行. #!/bin/bash # 要备份的数据库名,多个数据库用空格分开 databases=(db1 ...
- typedef与define基本使用
参考: typedef用法 http://www.cnblogs.com/ggjucheng/archive/2011/12/27/2303238.html#define用法:http://blog. ...
- 13个小技巧帮你征服Xcode
本文由CocoaChina翻译组成员唧唧歪歪(博客)翻译自David McGraw的博客原文:13 Xcode Tips That Will Help You Conquer Xcode当谈论到iOS ...
- bss段为什么需要初始化?
我们都知道bss段需要初始化,但是这是为什么呢? 通过浏览资料,我们都会发现,bss段是不会出现在程序下载文件(*.bin *.hex)中的,因为全都是0.如果把它们出现在程序下载文件中,会增加程序下 ...
- linux vi 使用
vi 有一般模式和编辑模式 如vi test.txt 是首先进入的一般模式,一般模式下只能进行复制.删除.粘贴文件数据, 在一般模式下按i .I.a.A.o.O 都能进入编辑模式,按下不同的键进入编辑 ...
- vs2010 使用SignalR 提高B2C商城用户体验(一)
vs2010 使用SignalR 提高B2C商城用户体验(一) 1.需求简介,做为新时代的b2c商城,没有即时通讯,怎么提供用户粘稠度,怎么增加销量,用户购物的第一习惯就是咨询,即时通讯,应运而生.这 ...
- MIME
http://www1.huachu.com.cn/read/readbookinfo.asp?sectionid=1000000558 http://www.jb51.net/hack/10623. ...
- front-end
http://info.1688.com/detail/1139720782.html http://segmentfault.com/q/1010000000136513 http://h5apps ...