- java.net.SocketException in Java with Examples
- java.net.SocketException: Network is unreachable: connect
- Solution 2
- Solution 3
- Solution 4
- Related videos on Youtube
- sajad
- Comments
- Java.Net.SocketException: Network Is Unreachable
- Possible Reasons and Solution for java.net.SocketException: Network is unreachable in Java
- Related Article — Java Exception
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:
java.lang.Object java.lang.Throwable java.lang.Exception java.io.IOException java.net.SocketException
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.
Implemented Interfaces: Serializable Direct Known Subclasses: BindException, ConnectException, NoRouteToHostException, PortUnreachableException
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:
Example 1: Server-side
java.net.SocketException: Network is unreachable: connect
You are facing a connection breakdown. Does this happen in 3G, WiFi or «plain» connection on a computer?
Anyway, you must assume that the connection may be lost from time to time, when writing your app. For example, with mobiles, this happens frequently in the tube, in basements, etc. With PC apps, this is less frequent but occurs sometimes.
A retry can be a good solution. And a clean error message that explains the network is not available at this moment too.
Solution 2
I faced situation of getting java.net.SocketException not sometimes but every time. I’ve added -Djava.net.preferIPv4Stack=true to java command line and my program started to work properly.
Solution 3
I haven’t tested with your code so it would be totally different case though, still I’d like to share my experience. (Also this must be too late answer though, I hope this answer still would help somebody in the future)
I recently faced similar experience like you such as some times Network is unreachable, but sometimes not. In short words, what was cause is too small time out. It seems Java throws IOException with stating «Network is unreachable» when the connection fails because of it. It was so misleading (I would expect something like saying «time out») and I spent almost a month to detect it.
Here I found another post about how to set time out. Alternative to java.net.URL for custom timeout setting
Again, this might not the same case as you got experienced, but somebody for the future.
Solution 4
«Network is unreachable» means just that. You’re not connected to a network. It’s something outside of your program. Could be a bad OS setting, NIC, router, etc.
Related videos on Youtube
sajad
Comments
static void download (String url , String fileName) throws IOException< FileWriter xmlWriter; xmlWriter = new FileWriter(fileName); System.out.println("URL to download is : " + url); // here Exception is thrown///////////////////////////////// BufferedReader inputTxtReader = new BufferedReader (new BufferedReader(new InputStreamReader(addURL.openStream()))); //////////////////////////////////////////////////////// String str ; String fileInStr = ""; str = inputTxtReader.readLine(); while (!(str == null) )//&& !(str.equals("")) fileInStr += (str + "\r\n"); str = inputTxtReader.readLine(); > xmlWriter.write(fileInStr); xmlWriter.flush(); xmlWriter.close(); System.out.println("File Downloaded"); >
java.net.SocketException: Network is unreachable: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) at java.net.Socket.connect(Socket.java:518) at java.net.Socket.connect(Socket.java:468) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:389) at sun.net.www.http.HttpClient.openServer(HttpClient.java:516) at sun.net.www.http.HttpClient.(HttpClient.java:233) at sun.net.www.http.HttpClient.New(HttpClient.java:306) at sun.net.www.http.HttpClient.New(HttpClient.java:318) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:788) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:729) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:654) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:977) at java.net.URL.openStream(URL.java:1009) at MessagePanel.download(MessagePanel.java:640) at WelcomThread.run(MainBody2.java:891)
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):
//import required libraries import java.io.*; import java.net.URL; //Main class public class Main //download method static void downloadXML (String webUrl, String file) throws IOException //create object FileWriter xmlFileWriter; xmlFileWriter = new FileWriter(file); System.out.println("URL used for downloading the file is : " + webUrl); // this statement throws an Exception BufferedReader inputTextReader = new BufferedReader ( new BufferedReader( new InputStreamReader( new URL(webUrl).openStream()))); //create and initialize variables String string ; String fileInString = ""; string = inputTextReader.readLine(); //read file while (string != null ) fileInString += (string + "\r\n"); string = inputTextReader.readLine(); > //write file xmlFileWriter.write(fileInString); xmlFileWriter.flush(); xmlFileWriter.close(); System.out.println("The File is Downloaded"); >//end download() function //main method public static void main(String[] args) try downloadXML("https://www.cellml.org/Members/stevens/docs/sample.xml", "downloadXML.xml"); >catch(IOException exception) exception.printStackTrace(); > >//end main >//end Main class
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.
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.