2

I tried connecting to an IP address (e.g. http://222.222.222.222:8080) and a URL (e.g. http://www.website.com) while my wiFi is disabled. I noticed that if I don't have a wiFi and I tried connecting to an IP address, it gives me a ConnectException error. On the other hand, if I don't have a wiFi and I tried connecting to a URL, it gives me an IOException error. Why am I receiving different Exception for the 2 cases when the only difference is I supplied an IP address for the first one and a URL for the other? Can someone enlighten me on this one? I am asking this for clarification.

Thank you!

Arci
  • 6,647
  • 20
  • 70
  • 98

1 Answers1

2

You're getting different errors because different steps are failing.

When you're trying to connect to port 80 of an IP address, it is a connect(2) system call that is failing. There are many different reasons why connect(2) could fail; you'll need to inspect the message from the exception to provide a good error message to the user.

When you're trying to connect to port 80 of a textual address, the libraries will first try to resolve the hostname into an IP address using getaddrinfo(3). The name resolution may or may not fail based on having network access -- if you were trying to connect to localhost, for example, no network access is usually required, as the nameservice lookup can be handled entirely on the local device. Because the nameservice failure happens because you cannot contact a nameserver, it makes sense to give a different error message (and exception), even if the underlying cause is the same for a given set of tests. You might not be able to contact the nameservers for any variety of reasons. Again, you'll need to inspect the message from the exception to give a good error message to the user.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • Thanks for your answer! If I understand your explanation correctly, Android has different steps for connecting to an IP address and a textual address? Since the 2 has different steps, the error message are handled differently? Trying to connect to a textual address means you still have to connect to a nameserver to resolve the ip address. If it wasn't able to retrieve the ip address from the nameserver, a different error message is returned. A ConnectException is only returned if you are already trying to an IP address but fails to establish a connection? – Arci Apr 01 '12 at 01:01
  • It isn't specific to Android; it's generic across all devices and platforms that support the TCP/IP family of protocols. The details of the error messages change from platform to platform, but in general you can get the _protocol_-level error quite easily -- translating that to a human-friendly piece of advice such as "Your modem is unplugged" or "The network cable is backwards" or "The WiFi router is down" is immensely difficult. – sarnold Apr 01 '12 at 01:05