java 网络协议(一)InetAddress和Socket(含源码)

1,ip地址和主机名互换
package getip;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class GetIP {

	public static void main(String[] args) {
		InetAddress addr= null;
		
		if(args.length==0){
			System.out.println("usage:java GetIP hostname");
			System.exit(1);
		}
		try {
			addr = InetAddress.getByName(args[0]);
			
		} catch (UnknownHostException e) {
			System.out.println("I can't find"+args[0]);
			System.exit(2);
		}
//		byte[] add = addr.getAddress(); //返回字节数组
//		for(byte i:add){
//			System.out.println(i);
//		}
		
		//		getHostName()返回主机名,getHostAddress()返回地址
		System.out.println(addr.getHostName()+"="+addr.getHostAddress());
		try {
			InetAddress[] allAddrs = InetAddress.getAllByName(args[0]);//一台主机可能对应多个ip
		for(InetAddress a:allAddrs){
	    	  System.out.println(a); //InetAddress.toString的隐含调用,自动输出 "主机名/ip地址"
	      }
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} 
	}
}


如果执行参数主机名为www.sina.com,结果如下
www.sina.com=121.194.0.206
www.sina.com/121.194.0.206
www.sina.com/121.194.0.207
www.sina.com/121.194.0.208
www.sina.com/121.194.0.209
www.sina.com/121.194.0.210
www.sina.com/121.194.0.203
www.sina.com/121.194.0.205

2,测试连接某个服务,如web服务器
package testConn;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//测试连接web服务器
public class WebPing {
	public static void main(String[] args) {

		try {
			InetAddress addr= null;
			Socket socket = new Socket(args[0],80);//80端口是web服务
			addr=socket.getInetAddress();
			System.out.println("connected to "+addr);
			socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("can't connect to "+args[0]);
		}
	}

}

参数为www.sina.com结果
connected to www.sina.com/121.194.0.206
如果端口被占用出现,如参数为localhost时
can't connect to localhost

3,扫描出计算机正在使用的端口号
package usedport;

import java.io.IOException;
import java.net.ServerSocket;

//扫描出计算机中正在使用的端口,使用ServerSocket构造函数是否有异常判断
public class LocalScan {

	public static void main(String[] args) {
		for (int i = 0; i < 1023; i++) {
			testPort(i);
		}
		System.out.println("completed! ");
	}
	private static void testPort(int i) {
		try {
			ServerSocket server = new ServerSocket(i);
		} catch (IOException e) {
			System.out.println("Port " + i + " in use!");
		}
	}
}


结果:
Port 135 in use!
Port 445 in use!
。。。
。。。
completed!

你可能感兴趣的:(java,.net,Web,socket,网络协议)