Open In App

How to Fix Connection refused: connect in Java?

Last Updated : 04 Feb, 2022
Like Article
Report 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 Connection refused.

  1. 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.
  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 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 Program to Illustrate Creation of ConnectException
// Importing required classes
import java.util.*;
// Main class
// To test hostname and port connectivity
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
        String hostname = "";
        // 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 =
                   != -1) {
        // 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
                "Connection Refused Exception as the given hostname and port are invalid : "
                + ex.getMessage());


Example 2: MySQL connectivity Check


// Java Program to Demonstrate DB Connection Setup
// Importing basic libraries
import java.util.*;
// Step 1: Importing DB
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 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
    // Registering driver using DriverManager
    con = DriverManager.getConnection(url1 + db, dbUser,
    // 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
        "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.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads