问题
I'm trying to resolve a host name to its' corresponding IP.
My environment is a mac in a corporate network behind a proxy server, which is configured with a .pac file via the system preferences (automatic proxy configuration). So far everything is working fine and I can access resources inside and outside my corporate network.
Resolving hosts within my network works perfectly fine:
InetAddress.getByName("host.local");
But when I use external host names, I get a UnknownHostException:
InetAddress.getByName("google.com");
produces
Exception in thread "main" java.net.UnknownHostException: google.com
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:850)
at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1201)
at java.net.InetAddress.getAllByName0(InetAddress.java:1154)
at java.net.InetAddress.getAllByName(InetAddress.java:1084)
at java.net.InetAddress.getAllByName(InetAddress.java:1020)
at java.net.InetAddress.getByName(InetAddress.java:970)
at Test.main(Test.java:67)
(I'm a little bit surprised about Inet6AddressImpl
here)
As far as I understand is InetAddress.getByName using the native mechanisms to resolve host names. So I don't think that the error is caused by a missing proxy configuration within the java jvm.
But what else can it be, if everything else is working fine?
Some (maybe) useful additional information:
I'm using a MacBook,
ifconfig
shows the interfaces lo0, gif0, stf0, en0, fw0, en1 -> connected to the network, with ipv4 address.nslookup google.com
on the console returns** server can't find google.com: NXDOMAIN
The same code on a windows machine within the network produced the same Exception
Any ideas about the cause of this error? Or are there other ways to resolve host names in java?
回答1:
Your corporate DNS server prevents you from resolving any Interent domain ( they probably do not want people browsing non-corporate context ).
This is supported by the fact that your nslookup
query fails.
If you don't have a vote on your corporate policy, and your development machine has to stay on your company premises, there is nothing that you can do.
回答2:
As mentioned in this post, you can set custom DNS via a Sun-JVM only setting. I had this same resolution issue, but was able to ask the proxy explicitly for the lookup by settting it as the DNS server also. YMMV
System.setProperty("sun.net.spi.nameservice.nameservers", "<my-proxy-ip>");
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
回答3:
I know that this question has been updated, but because it is the top listed result in Google, I wanted to add this useful piece of information which might trip people up.
When using this method, remember the following.
http://www.google.com -- DOES NOT WORK
google.com -- WORKS!
来源:https://stackoverflow.com/questions/6911590/inetaddress-getbyname-fails-behind-proxy