Connecting a Java Socket to a Public IP Address

I need to make a server and a client that connects to the server.

Problem : "the server is running, the client can only connect to localhost, it cannot connect to the server on the Internet. I want the client to connect to the server through the public ip address on which the server is located."

First of all, I made sure that the port is redirected and accessible, I checked the port, and secondly, I completely disabled the firewall from the server machine.

below is the test code I'm using:

Server: nothing unusual is simple - ends if the client is connected, otherwise it just waits for a connection.

public class Server { public static void main(String args[]) { try { ServerSocket srvr = new ServerSocket(52000); srvr.accept(); } catch(Exception e) { e.printStackTrace(); } } } 

Client: I used no-ip.com to mask the ip server on "biogenserver2.noip.me". Using .getCanonicalHostName (); will return ip.

 public class Client { public static void main(String args[]) { try { String ip = Inet4Address.getByName("somets.noip.com").getCanonicalHostName(); InetSocketAddress sa = new InetSocketAddress(ip, 52000); //Socket skt = new Socket("0.0.0.0", 52000); //local - this works fine. Socket skt = new Socket(); skt.connect(sa); } catch(Exception e) { e.printStackTrace(); } } } 

When I start this server, the server connects perfectly, but the client returns a "connection timeout" exception

Any help would be appreciated. Thanks.

+5
source share
3 answers

Answer:

"Just for clarity: you checked that the port is open through the public IP address returned by no-ip, and the server will be without exception when you run this little testclient (on a machine that is not a server machine) - is that right? - fildor

TL: DR

Do not run the client and server on the same computer, and the same network is trying to connect to your server through your public IP address, and then to your own local network will result in a client timeout exception

I ran the client and server on the same computer, as well as on the same network. This caused a client timeout exception. I tried running the client on a different machine and on a different network, and I was able to successfully connect.

+2
source

What version of IP protocol is your application using? On linux you can figure it out with netstat -tunap | grep 52000 netstat -tunap | grep 52000 and see if the first field is tcp or tcp6 . If the latter, then it is possible that an IPv6 connectivity problem exists, and you may prefer to use IPv4 for IPv6 by specifying -Djava.net.preferIPv4Stack=true for the JVM.

0
source

It may take time for a three-way handshake to be completed, and a wait time for the client before the server accepts the client.

-1
source

Source: https://habr.com/ru/post/1240904/


All Articles