Java实现了FTP的简单功能,穿socks4代理的简单例子


import java.io.*;
import java.util.*;
import java.net.*;

public class SimpleFTP {
	protected static int proxySet=0;
	protected static String socks4Host=null;
	protected static int socks4Port=-1;
	protected static String socks4User=null;
	String host = null;
	int port = -1;
	BufferedReader in = null;
	PrintStream out = null;
	Socket socket = null;
	public SimpleFTP() {

	}

	public static void setSocks4Proxy(String host,String user){
		setSocks4Proxy(host,1080,user);
	}
	public static void setSocks4Proxy(String host,int port,String user){
		proxySet=1;
		socks4Host=host;
		socks4Port=port;
		socks4User=user;
	}
	public static Socket getSocket(String addr,int port)throws UnknownHostException,IOException{
		if(proxySet==1){
			return getSocks4Socket(addr,port);
		}
		else {
			return new Socket(addr,port);
		}
	}

	private static Socket getSocks4Socket(String address,int port)throws UnknownHostException,IOException{
		Socket s=new Socket(socks4Host,socks4Port);
		InetAddress ip=InetAddress.getByName(address);
		byte[] addr=ip.getAddress();
		byte[] user=socks4User.getBytes();
		byte[] header=new byte[9+user.length];
		header[0]=0x4;
		header[1]=0x1;
		header[2]=(byte)(port>>8);
		header[3]=(byte)port;
		System.arraycopy(addr,0,header,4,4);
		System.arraycopy(user,0,header,8,user.length);
		header[header.length-1]=0x0;
		//send request
		s.getOutputStream().write(header);
		byte[] response=new byte[8];
		s.getInputStream().read(response);
		//check whether available;if illegal ,the socket is already disconnected by server
		int CD=response[1];
		switch(CD){
		case 90:
			return s;
		case 91:
			throw new IOException("request rejected or failed");
		case 92:
			throw new IOException("request rejected becasue SOCKS server cannot connect to identd on the client");
		case 93:
			throw new IOException("request rejected because the client program and identd report different user-ids");
		default:
			throw new IOException("ERROR RESPONSE CODE:"+CD);
		}
	}

	public void open(String host,String user,String pass)throws IOException,UnknownHostException {
		open(host,21,user,pass);
	}

	public void open(String host, int port,String user,String pass) throws IOException,
			UnknownHostException {
		if (socket != null) {
			disconnect();
		}
		socket = getSocket(host, port);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintStream(socket.getOutputStream(), true);
		System.out.println("$"+in.readLine());
		if(user == null){
			user = "anonymous";
		}
		if(pass == null){
			pass = "anything";
		}
		String code = cmd("USER "+user);
		if(code.startsWith("331")){
			code = cmd("PASS "+pass);
			if(code.startsWith("230")){
				return ;
			}
		}
		else if(code.startsWith("230")){
			return ;
		}
		disconnect();
		throw new IOException("Authentication Failed");
	}

	public void noop(){
		cmd("NOOP");
	}

	public String pwd() throws IOException {
		String code = cmd("PWD");
		return code.substring(code.indexOf("\"")+1,code.lastIndexOf("\""));
	}

	public boolean cd(String dir) {
		String msg = cmd("CWD "+dir);
		if(msg != null && msg.startsWith("250")){
			return true;
		}
		else {
			return false;
		}
	}

	public boolean cdup() {
		String msg = cmd("CDUP");
		if(msg != null && msg.startsWith("250")){
			return true;
		}
		else {
			return false;
		}
	}

	public String[] ls()throws IOException{
		String path = pwd();
		Object[] params = pasv();
		out.println("LIST");
		byte[] data = readBytes((String)params[0],((Integer)params[1]).intValue());
		String str = new String(data);
		String[] ss = str.split("\n");
		String[] fs = new String[ss.length-3];
		for(int i=3; i<ss.length; i++){
			String postfix = (ss[i].startsWith("d"))? "/":"";
			String file = ss[i].substring(ss[i].lastIndexOf(" ")+1,ss[i].length()-1);
			fs[i-3] = path+"/"+file+postfix;
		}
		String msg = in.readLine();
		System.out.println("$"+msg);
		msg = in.readLine();
		System.out.println("$"+msg);
		return fs;
	}

	public int get(String remote_file,String local_file)throws IOException {
		if(!remote_file.startsWith("/")){
			remote_file = pwd()+"/"+remote_file;
		}
		Object[] params = pasv();
		out.println("RETR "+remote_file);
		FileOutputStream fos = new FileOutputStream(local_file);
		int size = readStream((String)params[0],((Integer)params[1]).intValue(),fos);
		fos.close();
		String msg = in.readLine();
		System.out.println("$"+msg);
		msg = in.readLine();
		System.out.println("$"+msg);
		return size;
	}

	public int put(String local_file,String remote_file)throws IOException {
		if(!remote_file.startsWith("/")){
			remote_file = pwd()+"/"+remote_file;
		}
		Object[] params = pasv();
		out.println("STOR "+remote_file);
		FileInputStream fis = new FileInputStream(local_file);
		int size = writeStream((String)params[0],((Integer)params[1]).intValue(),fis);
		fis.close();
		String msg = in.readLine();
		System.out.println("$"+msg);
		msg = in.readLine();
		System.out.println("$"+msg);
		return size;
	}

	public String cmd(String cmd){
		return cmd(cmd,true);
	}

	public String cmd(String cmd,boolean echo) {
		check();
		try {
			if(echo) System.out.println("$"+cmd);
			out.println(cmd);
			String ret = in.readLine();
			if(echo) System.out.println("$"+ret);
			if(ret.startsWith("421")){
				disconnect();
				return null;
			}
			return ret;
		}
		catch (Exception e) {
			return null;
		}
	}

	private Object[] pasv()throws IOException {
		String msg = cmd("PASV");
		//hardly return error code, I do none check here
		int[] nums = new int[6];
		msg = msg.substring(msg.indexOf("(") + 1, msg.lastIndexOf(")"));
		String[] ps = msg.split(",");
		for (int i = 0; i < nums.length; i++) {
			nums[i] = Integer.parseInt(ps[i]);
		}
		String host = nums[0]+"."+nums[1]+"."+nums[2]+"."+nums[3];
		int port    = nums[4]*256 + nums[5];
		Object[] os = new Object[2];
		os[0] = host;
		os[1] = new Integer(port);
		return os;
	}
	
	private byte[] readBytes(String host,int port)throws UnknownHostException,IOException{
		Socket s = getSocket(host,port);
		byte[] buffer = new byte[512];
		int pos = 0;
		int num;
		while((num = s.getInputStream().read(buffer,pos,buffer.length-pos)) != -1){
			pos += num;
			if(pos >= buffer.length){
				byte[] bs = new byte[pos+512];
				System.arraycopy(buffer,0,bs,0,pos);
				buffer = bs;
			}
		}
		s.close();
		if(pos >= buffer.length){
			return buffer;
		}
		else {
			byte[] bs = new byte[pos];
			System.arraycopy(buffer,0,bs,0,pos);
			buffer = null;
			return bs;
		}
	}

	private int readStream(String host,int port,OutputStream os)throws UnknownHostException,IOException {
		Socket s = getSocket(host,port);
		byte[] buffer = new byte[512];
		int total = 0;
		int num;
		int count = 0;
		long time = System.currentTimeMillis();
		long cur_time = time;
		long last = 0;
		while((num = s.getInputStream().read(buffer)) != -1){
			total += num;
			os.write(buffer,0,num);
			if(count%5 == 0){
				System.out.print("*");
			}
			cur_time = System.currentTimeMillis();
			if((cur_time-time-last) >10000){
				cmd("NOOP");
				System.out.print("\nSIZE:"+total/1024+" k\tkps=");
				last = cur_time - time;
				System.out.println(1000.0*total/1024/last);
			}
		}
		s.close();
		os.flush();
		return total;
	}

	private int writeBytes(String host,int port,byte[] data)throws UnknownHostException,IOException{
		Socket s = getSocket(host,port);
		s.getOutputStream().write(data);
		s.close();
		return data.length;
	}

	private int writeStream(String host,int port,InputStream is)throws UnknownHostException,IOException {
		Socket s = getSocket(host,port);
		byte[] buffer = new byte[512];
		int num = 0;
		int total = 0;
		while((num = is.read(buffer)) != -1){
			s.getOutputStream().write(buffer,0,num);
			total += num;
		}
		s.close();
		return total;
	}

	private void check() {
		if (socket == null) {
			throw new IllegalStateException("connection already disconnected");
		}
	}

	public void disconnect() {
		try {
			in.close();
			out.close();
			socket.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			socket = null;
		}
	}

	public static void main(String[] args) throws Exception {
		//ftp://www.175youxi.com:[email protected]/即时战略/帝国时代4合1.rar
		SimpleFTP ftp = new SimpleFTP();
		ftp.setSocks4Proxy("192.168.4.7","ruanjue");
		ftp.open("down.175youxi.com",21,"www.175youxi.com","11211");
		ftp.cd("即时战略");
		ftp.cmd("TYPE I");
		ftp.get("帝国时代4合1.rar","E:/game/帝国时代4合1.rar");
		ftp.disconnect();
		/*Socket socket = new Socket("192.168.1.161", 21);
		PrintStream out = new PrintStream(socket.getOutputStream(), true);
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.
				getInputStream()));
		String msg = in.readLine();
		System.out.println(msg);
		out.println("USER webdb");
		msg = in.readLine();
		System.out.println(msg);
		out.println("PASS apples");
		msg = in.readLine();
		System.out.println(msg);
		out.println("PWD");
		msg = in.readLine();
		System.out.println(msg);
		out.println("CWD /disk/web/");
		msg = in.readLine();
		System.out.println(msg);
		out.println("TYPE A");
		msg = in.readLine();
		System.out.println(msg);
		out.println("PASV");
		msg = in.readLine();
		System.out.println(msg);
		int[] nums = new int[6];
		msg = msg.substring(msg.indexOf("(") + 1, msg.lastIndexOf(")"));
		String[] ps = msg.split(",");
		for (int i = 0; i < nums.length; i++) {
			nums[i] = Integer.parseInt(ps[i]);
		}
		Socket s2 = new Socket(nums[0] + "." + nums[1] + "." + nums[2] + "." +
													 nums[3], nums[4] * 256 + nums[5]);
		out.println("RETR /disk/web/ruanjue/application/perl/study.pl");
		msg = in.readLine();
		System.out.println(msg);
		BufferedReader buffer = new BufferedReader(new InputStreamReader(s2.
				getInputStream()));
		String str = null;
		while ( (str = buffer.readLine()) != null) {
			System.out.println(str);
		}
		buffer.close();
		s2.close();
		ServerSocket server = new ServerSocket(nums[4] * 256 + nums[5]);
		out.println("PORT 192,168,4,124," + nums[4] + "," + nums[5]);
		msg = in.readLine();
		System.out.println(msg);
		out.println("LIST");
		msg = in.readLine();
		System.out.println(msg);
		s2 = server.accept();
		buffer = new BufferedReader(new InputStreamReader(s2.getInputStream()));
		str = null;
		while ( (str = buffer.readLine()) != null) {
			System.out.println(str);
		}
		buffer.close();
		s2.close();
		server.close();
		out.println("QUIT");
		msg = in.readLine();
		System.out.println(msg);
		out.close();
		in.close();
		socket.close();*/
	}
}

你可能感兴趣的:(java,Web,socket,OS,perl)