How to repair BindException: Cannot assign requested address? - java

I need to change the IP address of a host from a client.
I use UDP commands and a MulticastSocket to obtain the IP address of this host (currentIp) and use this IP address to successfully establish a TCP connection.
The command to change this host IP address requires a DatagramSocket since I need to first get the host device MAC address to include in the change IP address command. Once the TCP connection is made I close the MulticastSocket UDP socket so I can open the DatagramSocket but get the following error:
java.net.BindException: Cannot assign requested address: Cannot bind
Is there something I need to do besides close the MulticastSocket socket before trying to get a DatagramSocket socket with the same port number, or is am I missing something else?
DatagramSocket socket;
private boolean ChangeIpAddress(String newIp) {
DatagramSocket socket;
try {
socket = new DatagramSocket(30718, InetAddress.getByName(currentIp));
} catch (SocketException ex) {
...

It appears you are using a hostname with an incorrect IP address. You need to find you etc/hosts or where ever its defines.

In my case, I have changed the listening address to 127.0.0.1 (localhost) and the problem is fixed

Related

In which situation can I use getPort() in a DatagramSocket?

I'm using DatagramSockets to build a application and I stacked in a point of the code that I should identify which port my socket was bound. So in this part of my code:
dnsConnection = new DatagramSocket();
byte[] date = "\nSend me a available server IP!".getBytes();
pkg = new DatagramPacket(date, date.length, addr, port);
status.append("\nTrying to send the message to: " + addr.getHostAddress());
dnsConnection.send(pkg);
localPort = dnsConnection.getPort();
status.append("\nRequest has been sent to: " + addr.getHostAddress());
status.append("\nthrough the port: " + localPort);
As you can see, I'm trying to get the port in which my socket was bound using the method getPort(). Reading the API, we have this statement:
public int getPort()
Returns the port number to which this socket is connected. Returns -1 if the socket is not connected.
In this sense I continue to search an alternative and I found the method getLocalPort() and in the API:
public int getLocalPort()
Returns the port number on the local host to which this socket is bound.
Then using getLocalPort() I could have gotten the port in which my socket is bind, and I understood that getPort() is probably to get the port that the socket is connected, i.e., the port of the host in which I want to send information. After all this, grew up a question on my head:
As UDP is conectionless, in which moment can I use getPort() to recovery the port in which my socket is connected?
Maybe I understood wrong and getPort() is not related with the remote host, if I'm wrong please clarify-me.
That is.
Thanks.
Pablo
When you call dnsConnection.send(pkg), the DatagramPacket pkg includes information of the IP address of the remote host, and the port number on the remote host. When you later call dnsConnection.getPort(), it just returns the remote port number of the last sent packet, which is local information.

What does "Creates a socket address from an IP address" mean?

I was reading the javadoc for InetSocketAddress at http://docs.oracle.com/javase/8/docs/api/ and was wondering what the following phrase means:
Creates a socket address from an IP address and a port number.
What I want to do is create a socket on the local box that listens for incoming connections on the same port and begins communication with that client. I was using "localhost"/80 for the host name on my server, but netstat -l doesn't show anything listening on port 80.
Am I going about this the wrong way?
Then you need to create a ServerSocket.
From memmory: It is something like
ServerSocket mySocket =new ServerSocket(1234); // Listen on port 1234 on all network interfaces.
Socket incommingSocket=mySoccket.accept(); // Wait until a client connect. Once a client connect return the socket for the connection.
And then you can call getInputStream/getOutputStream on the incommingSocket object.

Java, DatagramPacket receive, how to determine local ip interface

Here's simple case when binding to all ip interfaces and specific udp port:
int bindPort = 5555; // example, udp port number
DatagramSocket socket = new DatagramSocket(bindPort);
byte[] receiveData = new byte[1500];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
...
socket.receive(receivePacket);
How do I know on which ip interface I received packet ?
I can see there is getSocketAddress():
Gets the SocketAddress (usually IP address + port number) of the
remote host that this packet is being sent to or is coming from.
but that returns remote ip+port. I would like to know local ip (local port is 5555 in this example).
Is it possible with std. Java libraries ?
I know this problem. For clarifying the purpose of this: You receive a packet over UDP (normally some kind of discovery implementation) and want return an anwer like ("Dear client, please download the file from http://<wtf-is-my-ip>:8080/thefile.txt"). My machine has three IPs: 127.0.0.1, 192.168.x.x and 10.x.x.x and the goal is to find out that the remote client sent the UDP packet to 192.168.x.x and that this must be the IP which will also work for another connection.
From the weupnp project I found the following code, which is not perfect but worked for me:
private InetAddress getOutboundAddress(SocketAddress remoteAddress) throws SocketException {
DatagramSocket sock = new DatagramSocket();
// connect is needed to bind the socket and retrieve the local address
// later (it would return 0.0.0.0 otherwise)
sock.connect(remoteAddress);
final InetAddress localAddress = sock.getLocalAddress();
sock.disconnect();
sock.close();
sock = null;
return localAddress;
}
//DatagramPacket receivePacket;
socket.receive(receivePacket);
System.out.print("Local IP of this packet was: " + getOutboundAddress(receivePacket.getSocketAddress()).getHostAddress);
The code might return the wrong IP if you have multiple IPs in the same network or because of some advanced routing configuration. But so far it's the best I was able to find and it's enough for most situations.
You can use a combination of NetworkInterface and InetAddress classes in order to get the details of your network.
NetworkInterface
InetAddress

connection refused exception in socket programming

In simple socket programming in java , what ip should be given while making new socket and its on wan
//Server side
ServerSocket ss = new ServerSocket(8888);
System.out.println("\n\n\tWaiting for connection\n");
Socket c = ss.accept();
System.out.println("\n\n\tConnection established\n");
//Client side
Socket c=new Socket("192.16*****",8888);
System.out.println("\n\n\tSuccessfully connected to the server");
//in **** there is complete ip address of my computer .... i.e. IPV4 address (checked
//from ipconfig command on cmd)
By default, a new ServerSocket should bind to all network interfaces.
You should be able to find out what interfaces are being used by running (I assume you're running Windows, since you mentioned ipconfig):
netstat -an |find /i "8888"
If in fact the application is creating a socket and binding to all interfaces, you should see an entry like the following:
TCP 0.0.0.0:8888 0.0.0.0:0 LISTENING
Otherwise, you should be able to get the interface that is being used (it's the first IP address from the left).

How to bind remote socket address in DatagramSocket

How to Set Remote Machine address in the UDP socket, That should be returned while the receiver getting the socket address?
My Code:
DatagramSocket socket = new DatagramSocket();
packet = new DatagramPacket(new byte[10],10);
packet.setAddress(InetAddress.getByName(hostName));
packet.setPort(portNum);
byte[] data = message.getBytes();
packet.setData(data);
packet.setLength(data.length);
socket.send(packet);
socket.close();
But this create a socket with my local address, receiver receives my address instead of that remote host address.
What is the solution for this?
You are the one making the request, so your address will be the one that gets submitted for the response. If you are wanting the remote machine to receive the response, the UDP connection (Datagram Socket Connection) must be established by the remote machine and not your own.

Categories