Reputation: 18159
I am learning about socket programming with Java. Using Java 8, have this simple server:
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("MY IP address is " + InetAddress.getLocalHost().getHostAddress());
ServerSocket server = new ServerSocket(4031);
Socket socket = server.accept();
System.out.println("Yay somebody connected! " + socket);
socket.close();
server.close();
}
}
All it does is show the host's address and then wait for a socket to connect.
And have this client:
import java.net.Socket;
public class Main {
public static void main(String[] args) throws Exception {
System.out.println("Trying to connect...");
Socket s = new Socket("123.456.7.890", 4031);
System.out.println("Cool");
s.close();
}
}
When I run the server and the client in my house (in two different computers), this works: I simply grab the IP address displayed by the server, supply it to the client, and the connection is established.
Now I have this same server in my house, whereas I am running my client in the office. Under the same process, I supplied the IP address printed by the server to my client. However, the connection is never established: neither the server or the client generate a socket.
The above points seem to suggest that the issue is with the IP address I used to connect to my server. Maybe InetAddress.getLocalHost().getHostAddress()
is not suitable for this - although it puzzles me why does this work with two machines in the same house.
What is it that I'm doing wrong?
Upvotes: 2
Views: 10491
Reputation: 421220
You say that your firewalls are turned off on both machines, but you also have to make sure that
you connect to your public IP. The IP that your server reports is probably the LAN IP that you've received from your router through DHCP
You also have to make sure that your router is configured to forward connections to port 4031 of your public IP to the IP of your server (and not to some other machine on your local network).
Finally, there's a small risk that your ISP forbids setting up servers at home. In this case they may be so evil that they block incoming connections.
Upvotes: 2