Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 15 Jul, 2021

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.

  1. As client and server involved, both should in a network like LAN or internet. If it is not present, it will throw an exception on the client-side.
  2. 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.
  3. Sometimes a server may be running but not listening on port because of some overridden settings etc.
  4. Usually, for security reasons, the Firewall will be there, and if it is disallowing the communication.
  5. By mistake, the wrong port is mentioned in the port or the random port generation number given.
  6. 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: Simple Java code which creates java.net.ConnectException

Java




// Main class
// TestHostNameAndPortConnectivity
public 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 estabilished
            // 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 libraries
import java.io.*;
import java.util.*;
// Step 1: Importing DB libearies
import.java.sql.*;
 
// Try block to check for exceptions
try {
 
    // Setting initial connection object to null
    Connection con = null;
 
    String driver = "com.mysql.jdbc.Driver";
 
    // Step 2: Loading and registering drivers
 
    // Here if IPADDRESS 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 noy 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 exceptions
catch (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.
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :