UnknownHostException

java.net.UnknownHostException – How to solve UnknownHostException

In this tutorial we are going to talk about java.net.UnknownHostException. This is a subclass of IOException, so it is a checked exception. It emerges when you are trying to connect to a remote host using its host name, but the IP address of that host cannot be resolved. So, this a straight forward situation.

1. A simple Client-Server application

To demonstrate this exception, I’m going to use the client-server application we’ve seen in java.net.ConnectException – How to solve Connect Exception. It creates two threads. The first one, SimpleServer, opens a socket on the local machine on port 3333. Then it waits for a connection to come in. When it finally receives a connection, it creates an input stream out of it, and simply reads one line of text from the client that was connected. The second thread, SimpleClient, attempts to connect to the server socket that SimpleServer opened. When it does so, it sends a line of text and that’s it.

UnknownHostExceptionExample.java:

package com.javacodegeeks.core.net.unknownhostexception;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class UnknownHostExceptionExample {

	public static void main(String[] args) {

		new Thread(new SimpleServer()).start();
		new Thread(new SimpleClient()).start();

	}

	static class SimpleServer implements Runnable {

		@Override
		public void run() {

			ServerSocket serverSocket = null;
			while (true) {
				
				try {
					serverSocket = new ServerSocket(3333);

					Socket clientSocket = serverSocket.accept();

					BufferedReader inputReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
					
					System.out.println("Client said :"+inputReader.readLine());

				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						serverSocket.close();
					
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}

	}

	static class SimpleClient implements Runnable {

		@Override
		public void run() {

			Socket socket = null;
			try {
				Thread.sleep(3000);
				
				socket = new Socket("localhost", 3333);
				
			    PrintWriter outWriter = new PrintWriter(socket.getOutputStream(),true);
			    
			    outWriter.println("Hello Mr. Server!");
			   

			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				
				try {
					socket.close();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
			}
		}

	}
}

As you can see, because I’m launching the two threads simultaneously, I’ve put a 3 second delay in SimpleClient for the client to wait before attempting to connect to the server socket, so as to give some time to server thread to open the server socket.

If you run the above program, after 3 seconds you will see an output like this :

Client said :Hello Mr. Server!

That means that the client, successfully connected to the server and achieved to transmit its text.

2. An example of UnknownHostException

Let’s see what happens when we change :

socket = new Socket("localhost", 3333);

to

socket = new Socket("local", 3333);

If you run the program again, this is the output:

java.net.UnknownHostException: local
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:579)
	at java.net.Socket.connect(Socket.java:528)
	at java.net.Socket.<init>(Socket.java:425)
	at java.net.Socket.<init>(Socket.java:208)
	at com.javacodegeeks.core.net.unknownhostexception.UnknownHostExceptionExample$SimpleClient.run(UnknownHostExceptionExample.java:64)
	at java.lang.Thread.run(Thread.java:744)

As you can see the IP address of the host "local" cannot be resolved, so an UnknownHostException is thrown.

3. How to solve UnknownHostException

UnknownHostException designates a pretty straight forward problem. That the IP address of the remote host you are trying to reach cannot be resolved. So the solution to this is very simple. You should check the input of Socket (or any other method that throws an UnknownHostException), and validate that it is the intended one. If you are not whether you have the correct host name, you can launch a UNIX terminal and use the nslookup command (among others) to see if your DNS server can resolve the host name to an IP address successfully. Here is an example :

nikos@nikos:~$ nslookup www.google.com
Server:		127.0.1.1
Address:	127.0.1.1#53

Non-authoritative answer:
Name:	www.google.com
Address: 173.194.39.209
Name:	www.google.com
Address: 173.194.39.210
Name:	www.google.com
Address: 173.194.39.212
Name:	www.google.com
Address: 173.194.39.211
Name:	www.google.com
Address: 173.194.39.208

nikos@nikos:~$ 

If you are on Windows you can use the host command. If that doesn’t work as expected then, you should check if the host name you have is correct and then try to refresh your DNS cache. If that doesn’t work either, try to use a different DNS server, eg Google Public DNS is a very good alternative.

Download Source Code

This was an example on java.net.UnknownHostException and how to solve UnknownHostException. You can download the source code of this example here : UnknownHostExceptionExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button