Java定义了操作服务器主机的ip和HostName的类 java.net.InetAddress,如下就是一个实例:
package com.dylan.java.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//此类中没有定义构造器,二是通过静态方法返回此类的对象实例
InetAddress ia = InetAddress.getLocalHost();
System.out.println(ia.getHostAddress());
System.out.println(ia.getHostName());
System.out.println(ia.getAddress());
//getCanonicalHostName()这个方法与getHostName()有什么不同呢?安全问题?
System.out.println(ia.getCanonicalHostName());
//InetAddress ia2 = new InetAddress(); 这个类没有构造方法吗?
System.out.println(InetAddress.getByName("www.baidu.com"));
/*
* 注意加上的(byte)是因为byte的方位是-128—128,没有加这个也是不会报错的
*/
byte[] bs = new byte[]{(byte)127,123,0,1};
InetAddress ia2 = InetAddress.getByAddress("dylan",bs);
System.out.println("第二种方法:"+ ia2.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}