Reputation: 41
We ran into same similar issue like: Java 11/17 HttpClient - How to try several IPs behind one hostname?
We have a Linux box that has localhost
IP address (127.XX.XX.XX
) followed by the internal IP address (192.XXX.XXX.XX
) listed in the /etc/hosts
file.
Server application when started up was bound to the internal IP address (192.XXX..
).
Our client application is based of Java 17 HttpClient
and the request is sent asynchronously just like below sample code.
Sample Code:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://hostname.domain:port/path"))
.header("Content-Type", "application/json")
.POST(json.body))
.build()
When our application ran on the same Linux box, we found that the HttpClient
library picked up 1st IP address (127.XXX.XXX.XX
) for 'hostname.domain'
and threw ClosedChannelException
.
Even if I iterate and get IP addresses of the 'hostname.domain'
, how can I bind 'hostname.domain'
to a particular IP address so that when socket channel is opened it's uses the specified IP address.
I rather use Java's inbuilt library and also since we were not aware of this shortcoming, it's a bit too late in the game to switch to Apache's HTTPClient.
Another thing I tried to circumvent this issue from client side was to enable server to bind to all IP4 and IPv6 addresses. This allowed the httpclient to then connect to the server. I'm not sure if this is a best practice and what issues that might pose.
Any help/advice/best practices to follow, greatly appreciated.
Thanks
Upvotes: 3
Views: 844
Reputation: 41600
You can use dnsjava to provide you the IP addresses that are available
Your request would need to pass the Host
variable
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://{ipaddress:port}/path"))
.header("Host", "hostname.domain")
.header("Content-Type", "application/json")
Upvotes: 0