55 (No Addresses for this interface.
56 Interface ppp0:
57 (No Addresses for this interface.
58 Interface eth0:
59 (No Addresses for this interface.
60 Interface eth1:
61 (No Addresses for this interface.
62 Interface eth2:
63 (No Addresses for this interface.
64 Interface ppp1:
65 (No Addresses for this interface.
66 Interface net4:
67 (No Addresses for this interface.
68 Interface eth3:
69 Address 10.24.194.17
70 Interface net5:
71 (No Addresses for this interface.
72 Interface net6:
73 (No Addresses for this interface.
74 Interface eth4:
75 Interface net7:
76 (No Addresses for this interface.
77 Interface net8:
78 (No Addresses for this interface.
79 Interface eth5:
80 Address 192.168.225.1
81 Interface eth6:
82 Address 192.168.220.1
83 Interface eth7:
84 (No Addresses for this interface.
85 Interface eth8:
86 (No Addresses for this interface.
88 (No Addresses for this interface.
89 Interface eth10:
90 (No Addresses for this interface.
91 Interface eth11:
92 (No Addresses for this interface.
93 Stephen-PC:
94 Stephen-PC/10.24.194.17
95 Stephen-PC/192.168.225.1
96 Stephen-PC/192.168.220.1
97 */
该示例代码通过两种不同的方式获取主机中网络设备的IPv4地址。由于我的电脑中安装了VMWare虚拟机软件,因此在只有一张物理网卡的情况下,却输出了更多的虚拟网络设备地址。
我们这里应用的第一种方式是通过JDK中提供的NetworkInterface类枚举出当前主机中所有的网络接口对象。其中每一个对象对应于一个网络接口设备,之后再通过枚举出的每个NetworkInterface对象获取与该设备关联的设备名称(iface.getName())和基于该设备设定的全部IP地址(iface.getInetAddresses())。和第一种方式不同的是,第二种方式通过主机名称直接获取了InetAddress对象数组,再通过遍历数组中的每一个元素获取相关设备的IP地址。和第一种方法相比,第二种方法可以根据主机名称获取网络中任意主机的IP地址信息,而第一种方式只能获取当前主机的网络地址信息。
2. TCP套接字--客户端:
Java为TCP协议提供了两个Socket类:Socket和ServerSocket。他们分别表示客户端和服务器的Socket对象。Socket对象中包含的数据是通讯类型(TCP/UDP)、远端IP地址(Client)/本地监听IP地址(Serve)、端口号等。其中IP地址和端口号都是通过InetAddress对象获取的。在开始通讯之前,要建立一个TCP连接,这需要先由客户端TCP向服务器端TCP发送连接请求。ServerSocket实例则监听TCP连接请求,并为每个请求创建一个新的Socket实例。也就是说,服务器端要同时处理ServerSocket和Socket实例,而客户端只需要使用Socket实例。下面我们还是从一个简单的TCP客户端的例子开始。
典型的TCP客户端要经过如下三步:
1) 创建一个Socket实例:构造函数向指定的远程主机和端口建立一个TCP连接
2) 通过套接字的输入输出流(I/O Streams)进行通信:一个Socket连接实例包括一个InputStream和OutputStream,它们的用法同于其他Java输入输出流。
3) 使用Socket类的close()方法关闭连接。
1 public class MyTest {
2 public static void main(String[] args) throws UnknownHostException, IOException {
3 String server = "10.24.194.17";
4 byte[] data = "HelloWorld".getBytes();
5 int port = 5050;
6 //1. 用指定的IP和Port构造服务器的Socket对象。如果这里不给出server和port的话,
7 //后面就需要显示的调用socket.connect(),并在该方法中传入这两个参数。
8 Socket socket = new Socket(server,port);
9 System.out.println("Connected to server... sending to string");
10 //2. 基于该Socket对象上的数据通道,获取输入和输出流对象,便于之后的数据读取和写出。
11 InputStream in = socket.getInputStream();
12 OutputStream out = socket.getOutputStream();
13 //3. 写数据到服务