创建 InetAddress 对象的四个静态方法
package InetAddressClass; import java.net.InetAddress; import java.net.UnknownHostException; public class InetAddressStaticMethod { public static void main(String[] args) { InetAddressStaticMethod._getLocalHost(); InetAddressStaticMethod._getByName("www.csdn.net"); InetAddressStaticMethod._getAllByName("www.baidu.com"); InetAddressStaticMethod._getByAddress(); } public static void _getLocalHost() { InetAddress localAddress = null; try { localAddress = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } System.out.println(localAddress); System.out.println(localAddress.toString().split("/")[1]); } public static void _getByName(String hostname) { InetAddress address = null; try { address = InetAddress.getByName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } System.out.println(address); System.out.println(address.toString().split("/")[1]); } public static void _getAllByName(String hostname) { InetAddress[] addresses = null; try { addresses = InetAddress.getAllByName(hostname); } catch (UnknownHostException e) { e.printStackTrace(); } for(InetAddress address : addresses) { System.out.println(address); System.out.println(address.toString().split("/")[1]); } } public static void _getByAddress() { byte[] ip = new byte[] { (byte)141, (byte)146, 8, 66 }; InetAddress address1 = null; try { address1 = InetAddress.getByAddress(ip); } catch (UnknownHostException e) { e.printStackTrace(); } System.out.println(address1); InetAddress address2 = null; try { address2 = InetAddress.getByAddress("Oracle website", ip); } catch (UnknownHostException e) { e.printStackTrace(); } System.out.println(address2); } // java.net.InetAddress.java -- source code: // public String toString() { // String hostName = holder().getHostName(); // return ((hostName != null) ? hostName : "") // + "/" + getHostAddress(); // } // public static InetAddress getByName(String host) // throws UnknownHostException { // return InetAddress.getAllByName(host)[0]; // } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。