Make a connection using an external IP address in Java

30,114

What you trying to do is a bit weird but it is possible.

You just need to know if your router supports NAT Loopback / NAT Reflection and activate it.

NAT-loopback

Also known as NAT-hairpinning or NAT-reflection. NAT-loopback is a feature in many consumer routers which allows a user to connect to its own public IP address from inside the LAN-network. This is especially useful when a website (with domain) is hosted at that IP address.

Share:
30,114

Related videos on Youtube

Shelef
Author by

Shelef

Updated on February 13, 2020

Comments

  • Shelef
    Shelef about 4 years

    I'm trying to build a chat program. I wrote the code and everything worked and still works great when I'm using my computer and connecting using 127.0.0.1. I also succeeded to connect successfully between my laptop and my computer, which run on the same router. (I used an internal IP address to do this, 10.0.0.3).

    Now I'm trying to make a connection between my router and other routers. And to this I'm trying to connect to an external IP address. I do the port forwarding part through my router and I also made a static IP. When I run the code I always get a "connection refused error".

    Here is the code:

    MainServer.java:

    import java.util.*;
    import java.io.*;
    import java.net.*;
    
    public class MainServer {
      private ArrayList<Socket> sockets;
      public MainServer() {
        ServerSocket server_socket;
        try {
          server_socket = new ServerSocket(5005);
          sockets = new ArrayList<Socket>();
          System.out.println("server is now running");
          while(true) {
            Socket socket = server_socket.accept();
            sockets.add(socket);
            try {
              PrintWriter writer = new PrintWriter(socket.getOutputStream());
              writer.println("---you are connected to the server---\r\n");
              writer.flush();
            } catch(Exception e) {e.printStackTrace();}
            System.out.println("server connected to " + socket.getInetAddress());
            Reader reader = new Reader(socket);
            Thread thread = new Thread(reader);
            thread.start();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    
      public static void main(String[] args) {
        MainServer server = new MainServer();
      }
      class Reader implements Runnable {
        Socket socket;
        public Reader(Socket socket) {
          this.socket=socket;
        }
        public void run() {
          while(true) {
            try {
              InputStreamReader stream_reader = new InputStreamReader(socket.getInputStream());
              BufferedReader reader = new BufferedReader(stream_reader);
              while(true) {
                String str = reader.readLine();
                if(str==null)
                  continue;
                System.out.println("message from the client " + socket.getInetAddress() + ": " + str);
                send_back_message(str);
              }
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }
        public void send_back_message(String str) {
          try {
            for(Socket send_to_socket: sockets) {
              PrintWriter writer = new PrintWriter(send_to_socket.getOutputStream());
              writer.println(send_to_socket.getInetAddress()+ ": " + str);
              writer.flush();
            }
          } catch(Exception e) {e.printStackTrace();}
        }
      }
    }
    

    Client.java:

    public Client() {
      frame = new JFrame();
      JPanel panel = new JPanel();
      chat = new JTextArea(20,40);
      chat.setEditable(false);
      JScrollPane scroll = new JScrollPane(chat);
      text = new JTextField(32);
      JButton send = new JButton("Send");
      send.addActionListener(new SendButtonListener());
      panel.add(scroll);
      panel.add(text);
      panel.add(send);
      frame.getContentPane().add(panel);
      frame.setSize(500,500);
      frame.setVisible(true);
      try {
        socket = new Socket("77.126.189.65",5005);
      } catch (Exception e) {
        e.printStackTrace();
      }
      Thread thread = new Thread(new ClientReader());
      thread.start();
    }
    public static void main(String[] args) {
      Client client = new Client();
    }
    class SendButtonListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        try {
          PrintWriter writer = new PrintWriter(socket.getOutputStream());
          writer.println(text.getText());
          writer.flush();
          text.setText("");
        } catch (IOException e1) {
          e1.printStackTrace();
        }
      }
    }
    class ClientReader implements Runnable {
      public void run() {
        try {
          InputStreamReader stream_reader = new InputStreamReader(socket.getInputStream());
          BufferedReader reader = new BufferedReader(stream_reader);
          while(true) {
            String str = reader.readLine();
            if(str==null)
              continue;
            chat.setText(chat.getText() + str + "\r\n" );
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    }
    

    I also tried this tool. When I run the MainServer file and try the tool, I get a positive answer. I also get a positive on my own Eclipse. When my MainServer makes a successful connection, it prints a message about it using these lines:

    Socket socket = server_socket.accept();
    System.out.println("server connected to " + socket.getInetAddress());
    

    So every time I'm clicking the "check" button in the tool above, I get a message in my Eclipse console (system.out.println part):

    server connected to /69.163.149.200

    Therefore I think the problem is probably not connected to the MainServer or the portforwading/firewall/static IP.

    I also thought maybe the problem occurs because I'm trying connecting from my own router device to my own router. I will leave the MainServer file open for the next half hour so if someone can run the Client.java on his computer it will be helpful.

    • Davide Berra
      Davide Berra about 11 years
      in your tests... both client and server are behind the same router?
    • Shelef
      Shelef about 11 years
      yes i run the server and the client on the same eclipse same computer and same router
    • Mateusz Krzaczek
      Mateusz Krzaczek about 11 years
      If you are still inside LAN (as i understand) you have to use internal IP. If you are on the same computer, you have to use 127.0.0.1
    • Shelef
      Shelef about 11 years
      i dont realy understand what LAN is. i already used internal ip and it worked. the main point of the program is to connect between diffrent routers, so i use extenal ip. i trying to make a connection on my own computer only for checking if the program work when i use external ip.
  • mightyrick
    mightyrick about 11 years
    And you don't have a firewall running on the server at all?
  • Shelef
    Shelef about 11 years
    i dont think so. my port is open according this tool: yougetsignal.com/tools/open-ports
  • Shelef
    Shelef about 11 years
    can you try run the Client.java file on your own computer and i will know if it can connect (my server open)
  • mightyrick
    mightyrick about 11 years
    People should not be asking unknown parties to connect to their internal machines like this. Rife with security problems.
  • Shelef
    Shelef about 11 years
    ok thanks im actually dont want it. but now i understand that i cant connect my router on default to itself and thats why the program doesnt worked
  • Shelef
    Shelef about 11 years
    ok sorry for asking. acctually someone did connect to me and write some things
  • Shelef
    Shelef about 11 years
    by the way how can i buy or get free a server which can run java files. (im looking for something similar to website hosting)
  • Davide Berra
    Davide Berra about 11 years
    sorry... I don't know... i did a fast search in google an thousand appeared but i no experience in java hosting =(