0

I have created a small TCP server but it only connects to other computers on my LAN. I did forward the port but it is still not working.

connection method:

    private boolean connect(){
    try {
        socket = new Socket(InetAddress.getByName(ip), port);
        System.out.println("socket created");
        dataOutput = new DataOutputStream(socket.getOutputStream());
        dataInput = new DataInputStream(socket.getInputStream());
        accepted = true;
    } catch (IOException e) {
        System.out.println("Unable to connect to the server");
        return false;
    }
    System.out.println("Successfully connected to the server.");
    return true;
}

listen method:

    private void listenForServerRequest(){
    Socket socket = null;
    try{
        socket = serverSocket.accept();
        dataOutput = new DataOutputStream(socket.getOutputStream());
        dataInput = new DataInputStream(socket.getInputStream());
        accepted = true;
        System.out.println("client joined");

    }catch(IOException e){
        e.printStackTrace();
    }
}

opening the server:

    private void initializeServer(){
    try{
        serverSocket = new ServerSocket(port,8,InetAddress.getByName(ip));
    }
    catch(Exception e){
        e.printStackTrace();
    }
}
yssyss
  • 1
  • 1
  • You can see here: http://www.javatpoint.com/socket-programming – Rafiq Jun 14 '15 at 05:36
  • Related: http://stackoverflow.com/questions/1919990/cant-connect-to-my-server-when-i-put-in-my-ip-in-java and http://stackoverflow.com/questions/9048598/java-cant-connect-with-serversocket – Tot Zam Jun 14 '15 at 05:54
  • When you get an exception, print the exception. Not some vague message of your own devising. You're throwing away all the useful information. Please fix your code and edit the resulting exception and stack trace into your question. – user207421 Jun 14 '15 at 06:24

1 Answers1

1

It appears as if you're supplying an IP address to InetAddress.getByName(). It requires a host name. Specifically, it needs the host name corresponding to the network that the port is forwarded to. For example, if you're forwarding to your computer's (internal) ip address (say, 192.168.1.10), then it needs the host name that corresponds to that address (for example mycomputer.local). Java needs that host name to know what interface it should listen on. I'm surprised it worked at all.

If you do want to supply the IP address and not the host name, use InetAddress.getByAddress(byte[] addr) instead:

byte[] addr = new byte[4];
addr[0] = 192;
addr[1] = 168;
addr[2] = 1;
addr[3] = 10;
...
serverSocket = new ServerSocket(port,8,InetAddress.getByAddress(addr));
Alvin Thompson
  • 5,388
  • 3
  • 26
  • 39