Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a connection using an external IP address in Java

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.

like image 586
Shelef Avatar asked Feb 12 '13 15:02

Shelef


1 Answers

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.

like image 55
Davide Berra Avatar answered Nov 30 '22 14:11

Davide Berra