《Java TCP/IP Socket编程》读书笔记(2)

2.1 套接字地址

1. 在Java中,地址可以是IP地址也可以是主机名。

下面是一个Java中地址的例子

package com.suifeng.tcpip.chapter2;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * InetAddress 测试
 * @author suifeng
 *
 */
public class InetAddressExample {

	public static void main(String[] args) {
		// 获取网络接口和本机关联的地址
		try {
			Enumeration interfaceList = NetworkInterface.getNetworkInterfaces();
			
			if(interfaceList == null)
			{
				System.out.println("-----------No networkinterface founded-----------");
			}
			else
			{
				System.out.println("检查本地网卡设置:");
				while(interfaceList.hasMoreElements())
				{
					// 获取到一块网卡
					NetworkInterface networkInterface = interfaceList.nextElement();
					
					// 获取此网卡的地址
					Enumeration addressList = networkInterface.getInetAddresses();
					
					// 空列表检测
					if(!addressList.hasMoreElements())
					{
						continue;
						//System.out.println("\t No address for this interface");
					}
					
					// 数据每一块网卡的名称、IP类型及其地址
					System.out.println(networkInterface.getName());
					while(addressList.hasMoreElements())
					{
						InetAddress address = addressList.nextElement();
						System.out.println("\tAddress "+((address instanceof Inet4Address) 
								? "(IPV4)"
								: (address instanceof Inet6Address) ? "(IPV6)":"(?)" )+"\t"+address.getHostAddress());
					}
				}
					
			}
		} catch (SocketException e) {
			System.out.println("Error get network interface :"+e.getMessage());
			e.printStackTrace();
		}
		
		// 对于从命令行的输入数据打印出主机名及地址
		System.out.println("");
		for(String host : args)
		{
			System.out.println("Host:"+host);
			try {
				InetAddress[] addressList = InetAddress.getAllByName(host);
				
				for (InetAddress address : addressList) {
					System.out.println("\t"+address.getHostName()+"/"+address.getHostAddress());
				}
			} catch (UnknownHostException e) {
				System.out.println("unable to find address for:"+host);
			}
		}
	}

}

执行结果



InetAddress中有几个重要的方法,使用下面的程序再看一下

package com.suifeng.tcpip.chapter2;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * UDP 客户端
 * 
 * @author Suifeng
 * 
 */
public class UDPEchoClientTimeout
{
	// 超时时间
	private static final int TIMEOUT = 3000;
	// 最大连接次数
	private static final int MAXTRIES = 5;

	public static void main(String[] args) throws IOException
	{
		if (args.length < 2 || args.length > 3)
		{
			throw new IllegalArgumentException(
					"Paramters:  []");
		}

		// 服务器地址
		InetAddress serverAddress = InetAddress.getByName(args[0]);

		// 要发送的数据
		byte[] byteToSend = args[1].getBytes();

		// 服务器端口
		int serverPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;

		// UDP客户端
		DatagramSocket socket = new DatagramSocket();
		// 接收数据阻塞时间
		socket.setSoTimeout(TIMEOUT);

		System.out.println("UDP 客户端已建立....");
		
		// 发送数据报包
		DatagramPacket sendPacket = new DatagramPacket(byteToSend,
				byteToSend.length, serverAddress, serverPort);

		// 接收的数据报包
		DatagramPacket receiverPacket = new DatagramPacket(
				new byte[byteToSend.length], byteToSend.length);

		// 尝试接收次数
		int tries = 0;
		boolean receivedResponse = false;

		do
		{
			System.out.println("向服务区端发送数据....");
			// 向服务器端发送数据
			socket.send(sendPacket);

			try
			{
				System.out.println("接收从服务器端返回的数据...");
				// 从服务器端接收数据
				socket.receive(receiverPacket);

				if (!receiverPacket.getAddress().equals(serverAddress))
				{
					throw new IOException(
							"Received packet from an unknown source");
				}

				receivedResponse = true;
			}
			catch (InterruptedIOException e)
			{
				tries++;
				System.out.println("Timed out," + (MAXTRIES - tries)
						+ " more ties");
			}

		} while ((!receivedResponse) && (tries < MAXTRIES));

		if(receivedResponse)
		{
			System.out.println("Received:"+new String(receiverPacket.getData()));
		}
		else
		{
			System.out.println("No response--giving up!");
		}
	}

}

执行结果


你可能感兴趣的:(Java,TCP/IP,Socket)