java net unknownhostexception что это

java.net.UnknownHostException: Invalid Hostname for Server

Last modified: August 13, 2020

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Introduction

In this tutorial, we’ll learn the cause of UnknownHostException with an example. We’ll also discuss possible ways of preventing and handling the exception.

2. When Is the Exception Thrown?

UnknownHostException indicates that the IP address of a hostname could not be determined. It can happen because of a typo in the hostname:

The above code throws an UnknownHostException since the misspelled locaihost doesn’t point to any IP addresses.

Another possible reason for UnknownHostException is DNS propagation delay or DNS misconfiguration.

It might take up to 48 hours for a new DNS entry to be propagated all around the Internet.

3. How to Prevent It?

Preventing the exception from occurring in the first place is better than handling it afterward. A few tips to prevent the exception are:

4. How to Handle It?

UnknownHostException extends IOException, which is a checked exception. Similar to any other checked exception, we must either throw it or surround it with a try-catch block.

Let’s handle the exception in our example:

It’s a good practice to close the connection when UnknownHostException occurs. A lot of wasteful open connections can cause the application to run out of memory.

5. Conclusion

In this article, we learned what causes UnknownHostException, how to prevent it, and how to handle it.

As always, the code is available over on Github.

Источник

Unknown Host Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Thrown to indicate that the IP address of a host could not be determined.

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs a new UnknownHostException with no detail message.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs a new UnknownHostException with no detail message.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Handle

The handle to the underlying Android instance.

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Читайте также:  рейс su6471 какой самолет

Creates a localized description of this throwable.

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) ThresholdClass

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

Initializes the cause of this throwable to the specified value.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Prints this throwable and its backtrace to the standard error stream.

Sets the Handle property.

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Java Exception Handling – UnknownHostException

Next up in our comprehensive Java Exception Handling series we’ll be looking over the UnknownHostException. The UnknownHostException can be thrown in a variety of scenarios in which a remote connection fails due to an invalid or unknown host (i.e. IP, URL, URI, etc).

The Technical Rundown

All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein. The full exception hierarchy of this error is:

Full Code Sample

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

When Should You Use It?

Since the UnknownHostException only occurs when dealing with some kind of IO connection, most of our sample code will illustrate a basic example of how to establish a client/server connection. Thus, let’s start by going over the simple Server class:

Now, the client side is handled in the Client class:

Since both the client and server scripts effectively block other threads with infinite loops, we’ll need to establish two different threads to test this. We start by executing the Server class, creating a new server:

Читайте также:  размер 10хл мужской это какой

The client output shows that we successfully sent our message to the server. The Server output confirms that the message was received from the Client :

Now, let’s intentionally shut down this connection to localhost:24601 by using the «quit» keyword:

This closes the existing client connection and, per our code, establishes a new connection to localhose:24601 :

Notice the slight typo in the host name. We immediately see the output showing an intention to connect, followed by a brief pause and then an expected UnknownHostException is thrown:

As mentioned in the introduction, the UnknownHostException can occur for a variety of reasons, so this is just one example. In this case, the host localhose doesn’t exist, so no connection can be established. Note that this is specifically different from other connection errors where the host simply refuses connections, or hangs and eventually produces a timeout.

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

java.сеть.UnknownHostException: недопустимое имя хоста для сервера: локальный

какие шаги я должен предпринять для решения ошибки:

я добавил новое имя виртуального хоста в эмуляторе Android, но результат возвращается к

когда я набираю URL-адрес virtualhost на своем ПК, он работает на дисплее. Опять же, когда я запускал эмулятор и проверял Logcat, я не мог прочитать или проверить состояние HTTP, если 200, 202 или код ошибки. Он просто вернулся в UnknownHostException

12 ответов

на самом деле исключение говорит о том, что нет известного сервера с именем «local». Я предполагаю, что вы пытаетесь подключиться к локальному компьютеру. Попробуйте с именем хоста «localhost» вместо этого, или, возможно, 127.0.0.1 или ::1 (последний-IPv6).

брошенный, чтобы указать, что IP-адрес хозяина определить не удалось.

127.0.0.1 или ::1 или «localhost» всегда должен быть интерфейс loopback, поэтому, если это не сработает, я был бы очень удивлен.

для редактирования /etc/hosts файл и добавить следующий:

надеюсь, что это помогает.

java.сеть.UnknownHostException: хост не разрешен:

брошенный, чтобы указать, что IP-адрес хоста не может быть определен.

Читайте также:  dope style что это

это исключение также возникает, когда вы подключены к действительному wifi, но маршрутизатор не получает интернет. Его очень легко воспроизвести это:

вы обратите внимание на эту ошибку!!

Это может произойти по разным причинам

1) Проверьте, подключен ли VPN, вы можете получить эту ошибку иногда, если да

» ваше имя хоста, localhost разрешает адрес обратной связи: 127.0.0.1; используя 10.xxx.1.193 Вместо (на интерфейсе cscotun0)»

отсутствует имя хоста. JBoss использует эту переменную среды ($HOSTNAME) при подключении к серверу.

есть десятки вещей, которые могут вызвать это. Пожалуйста, прокомментируйте, если вы обнаружите новую причину.

для взлома, пока вы не сможете окончательно решить эту проблему на своем сервере, вы можете добавить строку до конца вашего файла / etc / hosts:

исключение, которое постоянно получалось, было:

независимо от того, как я пытался подключиться к любому действительному хосту, печать его в терминале тоже не поможет. Все было правильно.

Источник

java.net.UnknownHostException: Invalid hostname for server: local

What are the steps I should take to solve the error:

I added the new virtual host name at Android emulator but the result returns to

When I type my virtualhost URL on my PC, it works on display. Then again, when I ran on Emulator and check on Logcat, I couldn’t be able to read or check the HTTP status if 200, 202, or an error code number. It simply returned to UnknownHostException

13 Answers 13

For that edit /etc/hosts file and add following:

What the exception is really saying is that there is no known server with the name «local». My guess is that you’re trying to connect to your local computer. Try with the hostname «localhost» instead, or perhaps 127.0.0.1 or ::1 (the last one is IPv6).

Thrown to indicate that the IP address of a host could not be determined.

127.0.0.1 or ::1 or «localhost» should always be the loopback interface, so if that doesn’t work I’d be really surprised.

java.net.UnknownHostException: Host is unresolved:

Thrown to indicate that the IP address of a host could not be determined.

This exception is also raised when you are connected to a valid wifi but router does not receive the internet. Its very easy to reproduce this:

You will observe this error!!

The exception that was continuously received was:

No matter how I tried to connect to any valid host, printing it in the terminal would not help either. Everything was right.

Источник

Сказочный портал