套接字地址

来源:互联网 发布:mysql查看字符集 编辑:程序博客网 时间:2024/06/05 07:25

一个客户端要发起一次通信,首先必须知道运行服务器端程序的主机的IP地址或者是主机名,主机名必须被解析成数字型地址才能用来通信。

InetAddress类代表了一个网络地址,包括主机名和数字类型的地址信息。InetAddress实例是不可变的,一旦创建,每个实例就始终指向同一个地址。

该类有两个子类: Inet4Address 和 Inet6Address。

下面我给出一个示例程序,该示例程序利用了NetworkInterface类的基本用法。


package com.niepengfei.test;import java.net.InetAddress;import java.net.NetworkInterface;import java.util.Enumeration;public class InetAddressExample {public static void main(String[] args) throws Exception{//返回此机器上的所有接口。如果在此机器上找不到任何网络接口,则返回 null,一个主机对应多个网络接口列表,例如有线网接口,无线网接口还有其他类型的接口等Enumeration<NetworkInterface> interfaceList = NetworkInterface.getNetworkInterfaces();if(interfaceList != null){while (interfaceList.hasMoreElements()) {//获取每一个网络接口NetworkInterface networkInterface = interfaceList.nextElement();//打印网络接口的本地名称System.out.println("网络接口: "+networkInterface.getName());//一个便捷方法,返回一个具有绑定到此网络接口全部或部分 InetAddress 的 Enumeration。 //如果存在安全管理器,则对每个 InetAddress 调用其 checkConnect 方法。//只有 checkConnect 不抛出 SecurityException 的 InetAddress 才会在 Enumeration 中返回。 Enumeration<InetAddress> addrList = networkInterface.getInetAddresses();if(!addrList.hasMoreElements()){System.out.println("该网络接口没有地址对应。");}while (addrList.hasMoreElements()) {InetAddress inetAddress = addrList.nextElement();//返回一个字符串代表主机的数字型地址System.out.println("------>" + inetAddress.getHostAddress());}}}}}

测试结果:






0 0
原创粉丝点击