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<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 2: MySQL connectivity Check
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.