Eray Tuncer
Eray Tuncer

Reputation: 725

Java Socket Bind Error

I have been having trouble about socket usage in java. First of all, let me explain what I want to do with sockets in java. I want to connect my laptop over the Internet via it. My laptop has a server and a client must connect over the internet. Because I have a router to handle my local network and I do not want to lead a port on the router to my laptop, I need to follow the path "internet->router->localNetwork->mylaptop". The problem is I have found a way to use both the internet ip address and the local ip address; However, it throws an exception : "Exception in thread "main" java.net.BindException: Address already in use"

The code I try is :

InetAddress addr = InetAddress.getByName("XXX.XXX.XXX.XXX");
InetAddress local = InetAddress.getByName("YYY.YYY.YYY.YYY");
Socket socket = new Socket(addr, 1111, local, 1111); // The line I have got exception

With leading router port to my laptop, I can run this code for the similar purposes:

Socket socket = new Socket("XXX.XXX.XXX.XXX", 1111);

*Xs stand for internet ip address

*Ys stand for local ip address

*Codes are belongs to client side of code

Upvotes: 1

Views: 656

Answers (2)

user207421
user207421

Reputation: 310915

You don't need to specify the local address:port of the Socket, and you are doing so incorrectly. Remove the last two parameters.

Upvotes: 0

izstas
izstas

Reputation: 5064

As far as I understand, you have a router with Internet (WAN) IP XXX.XXX.XXX.XXX with NAT, and you have a laptop with Local (LAN) IP YYY.YYY.YYY.YYY connected to the router, and you assume that

Socket socket = new Socket(InetAddress.getByName("XXX.XXX.XXX.XXX"), 1111, InetAddress.getByName("YYY.YYY.YYY.YYY"), 1111);

Will connect to the laptop. That is not correct.

Documentation of the constructor of Socket class you are using tells:

Creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

That is not what you want.

You can't connect to a device behind NAT like this. You have to "lead a port on the router".

Upvotes: 3

Related Questions