Java.Net.SocketException: Network Is Unreachable
Today, we will discuss the possible reasons and solutions for the java.net.SocketException: Network is unreachable exception while programming in Java.
Possible Reasons and Solution for java.net.SocketException: Network is unreachable in Java
Example Code (Causing an Error):
In this code, we pass the URL and the fileName to the downloadXML() method that reads the .xml file from the specified URL and writes it into the given fileName , which is further saved on our local system.
Though this code example is syntactically and semantically correct but generates the java.net.SocketException: Network is unreachable exception. The error is self-explanatory that tells us the network is not available at the current moment.
The reason causing this error is the connection breakdown. It can happen in Wi-Fi, 3G, or plain internet connection on the machine (computer/laptop).
Whenever we get this error, we must assume that the internet connection is not stable and may be lost from time to time while writing our application.
For instance, this happens with mobiles frequently when we are in the basements or tube, etc. It also happens while using apps on a PC/laptop, but it is less frequent.
The second reason can be incorrect Port and/or HostName . Make sure both are correct.
Additionally, you must remember two more things that can help in error identification.
First, you will get a java.net.UnknownHostException error if you are completely disconnected from the internet
Usually, the Network is unreachable differs from the Timeout Error . In the Timeout Error , it can’t even find where it should go.
For instance, there can be a difference between having our Wi-Fi card off and no Wi-Fi.
Firstly, perform the usual fiddling with the firewall to ensure that the required port is open. Then, have a look into the network issues that you might have.
Turn off the firewalls and eliminate the obstacles such as routers and complications to make it work in the simplest scenario possible since it is a network-related issue, not code related problem.
Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.
How to Fix java.net.ConnectException: Connection refused: connect in Java?
java.net.ConnectException: Connection refused: connect is the most frequent kind of occurring networking exception in Java whenever the software is in client-server architecture and trying to make a TCP connection from the client to the server. We need to handle the exception carefully in order to fulfill the communication problem. First, let us see the possible reasons for the occurrence of java.net.ConnectException: Connection refused.
- As client and server involved, both should be in a network like LAN or internet. If it is not present, it will throw an exception on the client-side.
- If the server is not running. Usually ports like 8080, (for tomcat), 3000 or 4200 (for react/angular), 3306(MySQL), 27017(MongoDB) or occupied by some other agents or totally down i.e. instance not started.
- Sometimes a server may be running but not listening on port because of some overridden settings etc.
- Usually, for security reasons, the Firewall will be there, and if it is disallowing the communication.
- By mistake, the wrong port is mentioned in the port or the random port generation number given.
- Connection string information wrong. For example:
Connection conn = DriverManager.getConnection(“jdbc:mysql://localhost/:3306 ?” + “user= &password=
Implementation: Here we are using MySQL database connectivity and connection info should be of this format. Now let us see the ways to fixing the ways of java.net.ConnectException: Connection refused. Ping the destination host by using the commands as shown below:
There are tools like “Putty” are available to communicate, and it is a free implementation of Telnet and SSH for Windows and Unix.
Java Networking — Common Socket Exceptions
These socket issues arise out of application bugs, system settings or system load.
java.net.SocketException: No buffer space available (maximum connections reached?)
This exception is usually observed when connections are being made at a rapid rate. This exception can arise due to one of the following conditions:
- When the number of available ephemeral network ports available for the application are nil.
- When the system does not have enough main memory to support new connections (whenever a socket is created, a part of memory is allocated for its READ/SEND buffers from non-paged kernel memory).
Solution: In Windows, the number of ephemeral network ports can be increased as directed here to resolve the problem arising out of case 1). The only available solution for case 2) is to make sure that the network connections are closed properly by the applications. And make sure the rate at which the connections are created does not throttle the kernel memory. Currently there are no formally documented approaches available to increase non-paged kernel memory.
java.net.SocketException: Broken pipe (UNIX)
A broken pipe error is seen when the remote end of the connection is closed gracefully.
Solution: This exception usually arises when the socket operations performed on either ends are not sync’ed.
java.net.SocketException: Connection reset
This exception appears when the remote connection is unexpectedly and forcefully closed due to various reasons like application crash, system reboot, hard close of remote host. Kernel from the remote system sends out a packets with RST bit to the local system. The local socket on performing any SEND (could be a Keep-alive packet) or RECEIVE operations subsequently fail with this error. Certain combinations of linger settings can also result in packets with RST bit set.
java.net.SocketException: Too many open files
An attempt was made to open more than the maximum number of file descriptors allowed in this process. These file descriptors include various other entities along with sockets. This is implementation dependent and could be either globally, per process, or per thread. On Linux, this is designated by the number OPEN_MAX.
Solution: Monitor the application and keep a watch on this. These values may be configurable on certain implementations. On Linux, ulimit can be used.
=java.net.BindException: Address already in use: JVM_Bind/java.net.BindException: Address already in use: NET_Bind
In the case, where the exception arises while doing a socket bind. The reason is that the application is trying to bind a socket to a port/IP/protcol combination that is already in use.
Solution: Avoid this. netstat log will be of help in this case to confirm.
java.net.BindException: Address already in use: connect
In the case, where the exception arises while doing a socket connect. There are several explanations for this some of them complex, depending on the implementation. Nonetheless, the problem can best be summarized that no local port numbers are available to the client. This could be because there are a lot of active connections in the local system(also involves sockets in a reuse connections phenomenon) . Or a lot of ports are in TIME_WAIT state(period between closing a connection and releasing the resources).
Solution: Increase the number of available ports. But if the problem is that there are not many concurrent active connections but in TIME_WAIT state, then reducing the TIME_WAIT value is a solution. This is platform dependent. Please consult the OS documents more information.
java.net.SocketTimeoutException: connect timed out
Signals that a timeout has occurred on a socket read or accept. That means that this exception emerges when a blocking operation of the two, an accept or a read, is blocked for a certain amount of time, called the timeout. Let’s say that the socket is configured with a timeout of 5 seconds. If either the accept() or read() method, blocks for more than 5 seconds, a SocketTimeoutException is thrown, designating that a timeout has occurred. It is important to note that after this exception is thrown. the socket remains valid, so you can retry the blocking call or do whatever you want with the valid socket.
Hang in Socket Write call
This happens when the sockets write buffers do not contain enough free space to accommodate the send data. This usually means the other side of the connection is not reading the data. Another typical situation is that the other side of the connection died and our side is attempting to retransmit. The retransmit attempts will eventually run out and the write will unblock. These timeouts are usually 15 — 17 minutes, and it’s due to the exponential backoff retransmit:
java.net.SocketException in Java with Examples
SocketException is a subclass of IOException so it’s a checked exception. It is the most general exception that signals a problem when trying to open or access a socket. The full exception hierarchy of this error is:
As you might already know, it’s strongly advised to use the most specific socket exception class that designates the problem more accurately. It is also worth noting that SocketException, usually comes with an error message that is very informative about the situation that caused the exception.
What is socket programming?
It is a programming concept that makes use of sockets to establish connections and enables multiple programs to interact with each other using a network. Sockets provide an interface to establish communication using the network protocol stack and enable programs to share messages over the network. Sockets are endpoints in network communications. A socket server is usually a multi-threaded server that can accept socket connection requests. A socket client is a program/process that initiates a socket communication request.
java.net.SocketException: Connection reset
This SocketException occurs on the server-side when the client closed the socket connection before the response could be returned over the socket. For example, by quitting the browser before the response was retrieved. Connection reset simply means that a TCP RST was received. TCP RST packet is that the remote side telling you the connection on which the previous TCP packet is sent is not recognized, maybe the connection has closed, maybe the port is not open, and something like these. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags.
Now as of implementation it is clear that we need two programs one handling the client and the other handling the server. They are as follows:
java.net.ConnectException – How to solve Connect Exception
In this example we are going to discuss about one of the most common exceptions you will come across when dealing with network programming in Java: ConnectException . ConnectException is a subclass of SocketException , and that alone reveals that it is meant to inform you about an error that occurred when you tried to create or access a socket. To be more specific, ConnectException is an exception that you will see in the client side of your application and it can emerge when a client fails to create a connection with a remote server socket.
1. A simple Client-Server program
Here is a very simple Client-Server program. 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.
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 something like this :
That means that the client, successfully connected to the server and achieved to transmit its text.
2. Simple cases of ConnectException
What happens if the client attempts to connect to localhost , not in port 3333 that the server listens, but instead in port 1234 . To test that I will simply change line:
And run the program again.After 3 seconds, here’s what happens:
So there, immediately, you have one occasion that can trigger a java.net.ConnectException . The reason is that you, obviously trying to access a port on localhost that is not open.
Other examples that also trigger a java.net.ConnectException follow the same pattern more or less: You are attempting to make a connection on a remote socket and that connection is refused. The reason it’s refused can vary. In the above example, I’m trying to access a port on the local machine that simply doesn’t exist.
Same thing happens:
If you want to try this make sure, you put a valid existing IP address (or else you will get an UnknownHostException ). But the point is that again, we are trying to connect to a specific server to a specific port, but that port doesn’t exist of the server.
Another trivial example is to simply not start the server thread and just let the client run. You can change the IP and port values in the client to be in the “correct” configuration : socket = new Socket(«localhost», 3333); .
But don’t start the server thread:
The same thing happens:
In this case the server was not running at all, even though the client used the correct configuration.