package org.apache.commons.net;


import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

import org.apache.commons.net.DefaultSocketFactory;

/**
 * @author cch
 */
public class CustomSocketFactory extends DefaultSocketFactory
{
	private int connectionTimeout;
	
	public CustomSocketFactory(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}
	
	public Socket createSocket(String host, int port) throws UnknownHostException, IOException {
		return createSocket(host, port, null, 0);
	}

	public Socket createSocket(InetAddress address, int port) throws IOException {
		return createSocket(address.getHostName(),port, null, 0);	
	}

	public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) 
		throws IOException 
	{
		return createSocket(address.getHostName(), port, localAddress, 0);
	}

	public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws UnknownHostException, IOException {
		SocketFactory socketFactory = SocketFactory.getDefault();
        Socket socket = socketFactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, connectionTimeout);
        return socket;
	}
}


/*
 * $Log: SocketFactoryWrapper.java,v $
 */