I'm using squid proxy for ftp connections. On squid proxy we have rules based on hostname and the issue is that java is doing hostname resolution locally and then passing raw IP to the proxy.
So example code:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 9999));
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress("google.com", 21));
is creating a request like this:
CONNECT 172.217.23.142:21 HTTP/1.1
User-Agent: Java/14.0.1
Host: 172.217.23.142:21
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Proxy-Connection: keep-alive
So google.com
is already translated to 172.217.23.142 in CONNECT request. Is there some way to force java.net.Proxy to use hostname when opening communication with proxy server?
JSch lib that we use for ftps connections does this by default with ProxyHTTP
class and I basically need the same with java.net.Proxy
.
Use an unresolved socket address in Socket.connect
:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 9999));
Socket socket = new Socket(proxy);
socket.connect(InetSocketAddress.createUnresolved("google.com", 21));
The connect
method will use the IP address if it has been resolved already. You can see this in the implementation of HttpConnectSocketImpl
:
final InetSocketAddress epoint = (InetSocketAddress)endpoint;
String destHost = epoint.isUnresolved() ? epoint.getHostName()
: epoint.getAddress().getHostAddress();
final int destPort = epoint.getPort();