moomoohk
moomoohk

Reputation: 493

Connection refused when trying to connect with an external IP

I've been working on a little server/client project and I'm encountering a little problem which is hindering my progress.

I think I nailed the core the programs (the client and the server) and I managed to connect the two using localhost but when I try connecting through my external IP I get an exception:

java.net.ConnectException: Connection refused
java.net.PlainSocketImpl.socketConnect(Native Method)
java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
java.net.Socket.connect(Socket.java:529)
java.net.Socket.connect(Socket.java:478)
java.net.Socket.<init>(Socket.java:375)
java.net.Socket.<init>(Socket.java:218)
networking.Client.run(Client.java:183)
java.lang.Thread.run(Thread.java:680)

Initially I tried using port 10 but found out ports between 0 and 1023 don't work on Macs for some reason so I picked a port outside that range. Connecting with localhost worked but when I tried connecting with my external IP (just like a normal user would), I got that exception. My ports are forwarded properly and running sudo lsof -i tcp -nP (netstat for Macs) will show that in fact my server is actually listening on the correct port. This is leading me to believe that the problem might be with my client but I really don't know.

Here is the sudo lsof -i tcp -nP output from Terminal.app:

COMMAND     PID         USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java      35423 MeshulamSilk   41u  IPv6 0xc949f3cdb29dfdcd      0t0  TCP *:63370 (LISTEN)
java      35423 MeshulamSilk   42u  IPv6 0xc949f3cdbbf1b96d      0t0  TCP [::1]:63992->[::1]:63991 (TIME_WAIT)

I know these posts get kinda messy so I uploaded the code to Gist. If anyone would like me to add it here let me know and I will.

The code for both the server and client can be found here.

Some things to note:

If anyone knows what I'm doing wrong or what I'm simply not doing as well as anything else please let me know, I'd much appreciate it.

Upvotes: 3

Views: 2868

Answers (1)

Alberto Pires
Alberto Pires

Reputation: 319

I'm not an expert on Mac, but based on lsof's output, it seems like your program is binding on IPv6 only address. It'll work fine on localhost but if you try a public ip address (and use IPv4) it can be the source of your problem. As for the port number, on UNIX like OS you need to have root access to user ports below 1024. Any way, you should try to disable IPv6 on your Mac and see if the problem continues.

Upvotes: 1

Related Questions