How to Fix java.net.ConnectException: Connection refused: connect in Java?

04 Feb, 2022
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:
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<dbname>?” + “user=<username>&password=<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:
ping <hostname> - to test

ipconfig(for windows)/ifconfig(linux) - to get network configuration

netstat - statistical report
nslookup - DNS lookup name
There are tools like “Putty” are available to communicate, and it is a free implementation of Telnet and SSH for Windows and Unix.
Example 1: 
Java
// Java Program to Illustrate Creation of ConnectException // Importing required classesimport java.io;import java.net.*;import java.util.*; // Main class// To test hostname and port connectivitypublic class GFG {     // Main driver method    public static void main(String[] args)    {         // Hostname is defined so do have arbitrary        // localhost value which is nothing but 127.0.0.1        String hostname = "127.0.0.1";         // PORT is defined here        // It should have been 8080 or 8000 but cannot be 80         // If IP and PORT is invalid it will get exception        // Trying to connect        int port = 80;         // Try block to check for exceptions        try (Socket socket = new Socket(hostname, port)) {             // InputStream to read data from socket            InputStream inputStream                = socket.getInputStream();            InputStreamReader inputStreamReader                = new InputStreamReader(inputStream);             int data;             StringBuilder outputString                = new StringBuilder();             // Data read from input stream            while ((data = inputStreamReader.read())                   != -1) {                outputString.append((char)data);            }        }         // Catch block to handle the exceptions        catch (IOException ex) {             // If the given hostname and port number are            // invalid, connectivity cannot be established            // and hence error thrown Exception will happen            // when socket will not reachable            System.out.println(                "Connection Refused Exception as the given hostname and port are invalid : "                + ex.getMessage());        }    }}
Output:
Example 2: MySQL connectivity Check
Java
// Java Program to Demonstrate DB Connection Setup // Importing basic librariesimport java.io.*;import java.util.*; // Step 1: Importing DBimport java.sql.*; // Try block to check for exceptionstry {     // Setting initial connection object to null    Connection con = null;     String driver = "com.mysql.jdbc.Driver";     // Step 2: Loading and registering drivers     // Here if IP address is not your localhost,    // need to specify that or specific address    String IPADDRESS = "localhost"         // 3306 is port number        String url1        = "jdbc:mysql://IPADDRESS:3306/";     // If not suggesting that to assign generally is    // followed as DB = mySQL username= root, password=1234    String db = "<your dbname>";    String dbUser = "<username>";    String dbPasswd = "<password>";     // Loading driver using forName() method    Class.forName(driver).newInstance();    // Registering driver using DriverManager    con = DriverManager.getConnection(url1 + db, dbUser,                                      dbPasswd);     // Display message on the console    // when the connection is successfully setup    System.out.println("Database Connection Established");} // Catch block to handle the exceptionscatch (IOException ex) {     // Exception will happen when the IPAddress and port    // number are mismatch By pinging, we can correct that     // Display message on the console and    // getting exception message using getMessage() method    System.out.println(        "Connection Refused Exception as the given hostname and port are invalid : "        + ex.getMessage());}
Similarly, for other DB, we need to specify the correct port number i.e. 27017 for MongoDB be it in case of SSL (Secure socket layer) is there, prior checks of Firewall need to be checked and hence via coding we can suggest the solutions to overcome the exception 
Conclusion: As readymade commands like ping, telnet, etc are available and tools like putty are available, we can check the connectivity information and overcome the exception.
saurabh1990aror
anikaseth98
akshaysingh98088
adnanirshad158
solankimayank
sagartomar9927
gulshankumarar231
Java-Exceptions
Picked
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Check the OS Version in Linux?
How to Set Git Username and Password in GitBash?
How to Install and Use NVM on Windows?
How to Install Flutter on Visual Studio Code?
How to Install Jupyter Notebook on MacOS?
Arrays in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Split() String method in Java with examples