简体   繁体   中英

Java - TCP socket only connects in LAN

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();
    }
}

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM