InetAddress.getByName not working
I am looking for a computer named "Base" on the LAN However, I cannot find it and what comes back is an address from my ISP (so Net access is definitely working). The return is "Base/81.200.64.50". Basically, it cannot find the name. I'm using the emulator. The code I am using is a copy of Java code that runs on Windows, and that works fine - returns my LAN address. What am I 开发者_如何学Pythonmissing???
The code is:
InetAddress address = InetAddress.getByName(Constants.serverNameStr);
OK - the problem seems to be DNS lookup. If I replace "Base" with "www.google.com" I get 74.125.230.145, which is google. Seems the emulator cannot resolve the name using local router DNS. I have tried tweaking Settings on the emulator but no luck. Any ideas?
Also tried entering the DNS of the LAN router in the debug config of the emulator. No luck
I am having a similar problem with not being able to get any useful information from InetAddress.getByName(), but I did figure out a couple things that might be of use:
If you are using the DNS from your ISP (which you probably are) then your ISP may be giving you an IP address for one of its web sites when it cannot find the host that you requested. For example, Comcast returns an IP address of a real web page when it can't find the host. Most people who realize this do not want this behavior and you can fix it by changing the DNS addresses in your home router to point to Google's DNS servers. Use 8.8.8.8 and 8.8.4.4 (for the primary and secondary DNS servers.) Google's DNS servers are also generally faster and more secure. After you change the DNS servers in your router, then InetAddress.getByName() will throw an UnknownHostException when you ask for a host that it cannot find.
If you see a local machine name in the list of attached devices on your home router, you may need to add ".local" to the host name as the argument to InetAddress.getByName(). For example, Mac laptops will often have a hostname ending in ".local" but the router tables do not display that to the user. (At least, my NetGear router does not show the ".local" part of a hostname.)
This method fails on Android apps when run on the main thread. You need to create a runnable thread similar to:-
public static class GetIPAddresses extends java.lang.Thread {
public void run() {
int i = 0;
byte[][] addresses = new byte[20][];
try {
InetAddress[] machines = InetAddress.getAllByName("www.bing.com");
for (InetAddress address : machines) {
addresses[i++] = address.getAddress();
}
} catch (Exception e) { }
}
}
精彩评论