Home > Net >  Cannot Assign requested Address in AWS - JAVA Server Socket
Cannot Assign requested Address in AWS - JAVA Server Socket

Time:09-27

I'm making a call to the ServerSocket constructor with the following parameters.

ServerSocket ss = new ServerSocket(0, num, host);

The values of the variable are: num=5 & host=/56.224.235.106

And 56.224.235.106 is the IP adress of the machine the code resides on.

This line is causing the exception following exception: Error : java.net.BindException: Cannot assign requested address java.net.BindException: Cannot assign requested address

BTW, This is an AWS instance where I'm hosting 2 instances. I have one client and a server instance and there are 2 separate security groups for these instances where I have allowed TCP traffic from any iPV4 addresses.

How can I resolve this, is there an issue with my code or does my security group setting needs some change.

CodePudding user response:

In general you would not bind to the IP address directly. You would instead bind to all interfaces by not specifying a host. In this way you will respond to any incoming connections to the specified port. If I look at a Wildfly server I have running with Apache HTTPD in front of it I get:

$ netstat -na | grep LIST
tcp        0      0 0.0.0.0:8080            0.0.0.0:*               LISTEN     
tcp6       0      0 :::80                   :::*                    LISTEN    

In my case the Wildfly server is using IPv4 and Apache is using IPv6. But they are both listening on what is, for IPv4, 0.0.0.0. The O/S takes care of the external interface to internal address mapping.

If you truly only want to listen for external connections (i.e. you don't want someone on localhost connecting) then run the ifconfig command to determine what your "internal" IP is. For me I get:

$ ifconfig -a
ens5: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 9001
        inet 172.30.1.191  netmask 255.255.255.0  broadcast 172.30.1.255

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0

The 172.30.1.191 address is in a private IP address range (specifically what was called a Class B private network) and is maintained by Amazon. Listening on the IP that your machine uses will prevent connections from localhost.

  • Related