user1513200
user1513200

Reputation: 41

Java port forwarding

I am trying to design a very simple remote port forwarding Java program. When this program is complete and I run this in terminal (java PortForward 1234 google.com 80), the program should listen for a connection on 1234 and forward the traffic to 80 on the remote host google.com. I should then be able to point my browser to localhost:1234 and the browser should come up with google's page.

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

public class PortForward{
    public static void main(String argv[]) throws Exception{

        int portNum = Integer.parseInt(argv[0]);
        String hostName = argv[1];
        int hostportNum = Integer.parseInt(argv[2]);

        ServerSocket welcomeSocket = new ServerSocket(locportNum);  

        while(true){
            Socket conSocket = welcomeSocket.accept();

            BufferedReader inFromBrowser = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            DataOutputStream outToBrowser = new DataOutputStream(connectionSocket.getOutputStream());

            conSocket.close();
        }    
    }
}

What should my next step be?

Upvotes: 1

Views: 3435

Answers (3)

Kenneth Xu
Kenneth Xu

Reputation: 1514

Sorry for posting to an old question. But since it is not yet answered, I'm shamelessly referring you to my blog post. You'll find the source code (or binary jar file) that does exactly what you are trying to do.

http://kennethxu.blogspot.com/2006/04/java-based-tcpip-port-forwarding.html

Upvotes: 0

user207421
user207421

Reputation: 310913

You are writing an HTTP proxy. You don't need to, there are many freely available already, e.g. Apache Squid. However, if you must continue, when you accept a socket you need to start a thread to handle it. The first thing the thread does is to read an HTTP CONNECT command from the socket and get the target IP address. It should then open a socket to that address and send a failure reply to the accepted socket if necessary, otherwise it needs to start two more threads and then exit itself. The two threads both do the same thing: read from a socket and write to another socket. One of them reads from the accepted socket and writes to the target socket; the other does the other way around.

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143886

Ive been desperately searching and searching and searching and searching for any possible hint as to what to do next but i cant find anything useful. Please help. what should my next step be?

Your next step is to open a socket to hostName and port hostportNum. Then, you probably want to create some inFromHost and outToHost readers/streams. Then, you probably want to create a thread to read from browser and write to host, and another thread to read from host and write to browser.

Upvotes: 0

Related Questions