Ошибка java net connectexception connection refused connect

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    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 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 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

    import java.io;

    import java.net.*;

    import java.util.*;

    public class GFG {

        public static void main(String[] args)

        {

            String hostname = "127.0.0.1";

            int port = 80;

            try (Socket socket = new Socket(hostname, port)) {

                InputStream inputStream

                    = socket.getInputStream();

                InputStreamReader inputStreamReader

                    = new InputStreamReader(inputStream);

                int data;

                StringBuilder outputString

                    = new StringBuilder();

                while ((data = inputStreamReader.read())

                       != -1) {

                    outputString.append((char)data);

                }

            }

            catch (IOException ex) {

                System.out.println(

                    "Connection Refused Exception as the given hostname and port are invalid : "

                    + ex.getMessage());

            }

        }

    }

    Output:

    Example 2: MySQL connectivity Check

    Java

    import java.io.*;

    import java.util.*;

    import java.sql.*;

    try {

        Connection con = null;

        String driver = "com.mysql.jdbc.Driver";

        String IPADDRESS = "localhost"

            String url1

        String db = "<your dbname>";

        String dbUser = "<username>";

        String dbPasswd = "<password>";

        Class.forName(driver).newInstance();

        con = DriverManager.getConnection(url1 + db, dbUser,

                                          dbPasswd);

        System.out.println("Database Connection Established");

    }

    catch (IOException ex) {

        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.

    Last Updated :
    04 Feb, 2022

    Like Article

    Save Article

    I’m trying to implement a TCP connection, everything works fine from the server’s side but when I run the client program (from client computer) I get the following error:

    java.net.ConnectException: Connection refused
            at java.net.PlainSocketImpl.socketConnect(Native Method)
            at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
            at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
            at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
            at java.net.Socket.connect(Socket.java:529)
            at java.net.Socket.connect(Socket.java:478)
            at java.net.Socket.<init>(Socket.java:375)
            at java.net.Socket.<init>(Socket.java:189)
            at TCPClient.main(TCPClient.java:13)
    

    I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.

    The Server Code:

    //TCPServer.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPServer {
        public static void main(String argv[]) throws Exception {
            String fromclient;
            String toclient;
    
            ServerSocket Server = new ServerSocket(5000);
    
            System.out.println("TCPServer Waiting for client on port 5000");
    
            while (true) {
                Socket connected = Server.accept();
                System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
                        + ":" + connected.getPort() + " IS CONNECTED ");
    
                BufferedReader inFromUser = new BufferedReader(
                        new InputStreamReader(System.in));
    
                BufferedReader inFromClient = new BufferedReader(
                        new InputStreamReader(connected.getInputStream()));
    
                PrintWriter outToClient = new PrintWriter(
                        connected.getOutputStream(), true);
    
                while (true) {
    
                    System.out.println("SEND(Type Q or q to Quit):");
                    toclient = inFromUser.readLine();
    
                    if (toclient.equals("q") || toclient.equals("Q")) {
                        outToClient.println(toclient);
                        connected.close();
                        break;
                    } else {
                        outToClient.println(toclient);
                    }
    
                    fromclient = inFromClient.readLine();
    
                    if (fromclient.equals("q") || fromclient.equals("Q")) {
                        connected.close();
                        break;
                    } else {
                        System.out.println("RECIEVED:" + fromclient);
                    }
    
                }
    
            }
        }
    }
    

    The Client Code:

    //TCPClient.java
    
    import java.io.*;
    import java.net.*;
    
    class TCPClient {
        public static void main(String argv[]) throws Exception {
            String FromServer;
            String ToServer;
    
            Socket clientSocket = new Socket("localhost", 5000);
    
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
                    System.in));
    
            PrintWriter outToServer = new PrintWriter(
                    clientSocket.getOutputStream(), true);
    
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));
    
            while (true) {
    
                FromServer = inFromServer.readLine();
    
                if (FromServer.equals("q") || FromServer.equals("Q")) {
                    clientSocket.close();
                    break;
                } else {
                    System.out.println("RECIEVED:" + FromServer);
                    System.out.println("SEND(Type Q or q to Quit):");
    
                    ToServer = inFromUser.readLine();
    
                    if (ToServer.equals("Q") || ToServer.equals("q")) {
                        outToServer.println(ToServer);
                        clientSocket.close();
                        break;
                    } else {
                        outToServer.println(ToServer);
                    }
                }
            }
        }
    }
    

    Ashish Aggarwal's user avatar

    asked Jul 29, 2011 at 16:37

    Samantha Catania's user avatar

    Samantha CataniaSamantha Catania

    5,0665 gold badges37 silver badges69 bronze badges

    8

    This exception means that there is no service listening on the IP/port you are trying to connect to:

    • You are trying to connect to the wrong IP/Host or port.
    • You have not started your server.
    • Your server is not listening for connections.
    • On Windows servers, the listen backlog queue is full.

    tk_'s user avatar

    tk_

    16.2k8 gold badges80 silver badges90 bronze badges

    answered Jul 29, 2011 at 16:41

    Collin Price's user avatar

    Collin PriceCollin Price

    5,6103 gold badges33 silver badges35 bronze badges

    9

    I would check:

    • Host name and port you’re trying to connect to
    • The server side has managed to start listening correctly
    • There’s no firewall blocking the connection

    The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn’t, you need to work out why it hasn’t. Wireshark may help you on this front.

    answered Jul 29, 2011 at 16:39

    Jon Skeet's user avatar

    Jon SkeetJon Skeet

    1.4m861 gold badges9100 silver badges9174 bronze badges

    4

    You have to connect your client socket to the remote ServerSocket. Instead of

    Socket clientSocket = new Socket("localhost", 5000);

    do

    Socket clientSocket = new Socket(serverName, 5000);

    The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It’s not the name that is important, it’s all about IP addresses…

    user207421's user avatar

    user207421

    305k43 gold badges304 silver badges480 bronze badges

    answered Jul 29, 2011 at 17:21

    home's user avatar

    6

    I had the same problem, but running the Server before running the Client fixed it.

    answered Jul 25, 2012 at 18:09

    Dao Lam's user avatar

    Dao LamDao Lam

    2,82711 gold badges37 silver badges44 bronze badges

    3

    One point that I would like to add to the answers above is my experience

    «I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error«

    Point to note — When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response

    so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.


    To get IP for your local machine, you can use ipconfig command on cmd
    you will get IPv4 something like 192.68.xx.yy
    Voila ..that’s your machine’s IP where you have your server hosted.
    use it then instead of localhost

    http://192.168.72.66/my_api/login.php


    Note — you won’t be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

    answered Feb 26, 2018 at 16:50

    eRaisedToX's user avatar

    eRaisedToXeRaisedToX

    3,2012 gold badges22 silver badges28 bronze badges

    0

    I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.

    1. $ sudo vmq-admin listener show

    to show the list o allowed ips and ports for vernemq

    1. $ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000

    to add any ip and your new port. now u should be able to connect without any problem.

    Hope it solves your problem.
    enter image description here

    answered Apr 5, 2016 at 7:58

    MrOnyancha's user avatar

    MrOnyanchaMrOnyancha

    6055 silver badges28 bronze badges

    1

    Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn’t understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.

    The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.

    answered Nov 17, 2014 at 12:01

    phoenix's user avatar

    phoenixphoenix

    9853 gold badges17 silver badges38 bronze badges

    In my case, I gave the socket the name of the server (in my case «raspberrypi»), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)

    answered Dec 21, 2016 at 18:20

    Zhyano's user avatar

    ZhyanoZhyano

    3991 gold badge3 silver badges13 bronze badges

    In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

    answered Aug 23, 2017 at 13:42

    user1419243's user avatar

    user1419243user1419243

    1,6553 gold badges18 silver badges33 bronze badges

    i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)

    so be careful where to close your Socket

    user207421's user avatar

    user207421

    305k43 gold badges304 silver badges480 bronze badges

    answered May 21, 2016 at 21:07

    Basheer AL-MOMANI's user avatar

    I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
    This code works for me.

    ClientDemo.java

    public class ClientDemo {
        public static void main(String[] args) throws UnknownHostException,
                IOException {
            Socket socket = new Socket("127.0.0.1", 55286);
            OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
            os.write("Santosh Karna");
            os.flush();
            socket.close();
        }
    }
    

    and
    ServerDemo.java

    public class ServerDemo {
        public static void main(String[] args) throws IOException {
            System.out.println("server is started");
            ServerSocket serverSocket= new ServerSocket(55286);
            System.out.println("server is waiting");
            Socket socket=serverSocket.accept();
            System.out.println("Client connected");
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str=reader.readLine();
            System.out.println("Client data: "+str);
            socket.close();
            serverSocket.close();
    
        }
    }
    

    answered May 14, 2017 at 17:13

    Santosh Karna's user avatar

    Santosh KarnaSantosh Karna

    1191 gold badge3 silver badges12 bronze badges

    1

    I changed my DNS network and it fixed the problem

    answered Nov 23, 2019 at 9:51

    Elham Nikbakht's user avatar

    You probably didn’t initialize the server or client is trying to connect to wrong ip/port.

    answered Aug 10, 2020 at 16:21

    syclone's user avatar

    Change local host to your ip address

     localhost
     //to you local ip
     192.168.xxxx
    

    answered Apr 28, 2021 at 10:46

    Gabriel Rogath's user avatar

    Gabriel RogathGabriel Rogath

    6902 gold badges8 silver badges22 bronze badges

    I saw the same error message «»java.net.ConnectException: Connection refused» in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.

    Example of opening tunel:
    enter image description here

    Example of error in Squirrel with Postgresql:

    enter image description here

    It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.

    See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023

    answered Jan 6, 2022 at 19:57

    Genivan's user avatar

    GenivanGenivan

    1612 gold badges3 silver badges10 bronze badges

    In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as ‘localhost‘ in the server, and ‘[::1]‘ in the client. I don’t know why that is, but specifying ‘localhost’ in the client did not work.
    Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.

    answered Aug 12, 2022 at 15:07

    AlexeiOst's user avatar

    AlexeiOstAlexeiOst

    5644 silver badges13 bronze badges

    For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.

    In my case there was a problem with configured RestTemplate (it’s just an example):

    public RestTemplate localRestTemplate() {
       Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
       SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
       clientHttpReq.setProxy(proxy);
       return new RestTemplate(clientHttpReq);
    }
    

    I just simplified configuration to:

    public RestTemplate restTemplate() {
       return new RestTemplate(new SimpleClientHttpRequestFactory());
    }
    

    And it started to work properly.

    answered Jan 24 at 17:45

    HereAndBeyond's user avatar

    There is a service called MySQL80 that should be running to connect to the database

    for windows you can access it by searching for services than look for MySQL80 service and make sure it is running

    answered Jul 16, 2021 at 19:50

    MonirRouissi's user avatar

    It could be that there is a previous instance of the client still running and listening on port 5000.

    answered Jan 10, 2013 at 18:27

    Michael Munsey's user avatar

    Michael MunseyMichael Munsey

    3,7201 gold badge25 silver badges15 bronze badges

    2

    Ошибка java.net.ConnectException: Connection refused является одним из самых распространенных сетевых исключений в Java. Эта ошибка возникает, когда вы работаете с архитектурой клиент-сервер и пытаетесь установить TCP-соединение от клиента к серверу.

    Соединение также происходит в случае RMI (удаленного вызова метода), потому что RMI также использует протокол TCP-IP. При написании кода клиентского сокета на Java вы всегда должны обеспечивать правильную обработку этого исключения.

    В этом руководстве по Java вы узнаете, почему возникает исключение при отказе в соединении и как решить проблему.

    Причины

    ошибка java.net.ConnectException: Connection refused

    Отказ в соединении – это явный случай, когда клиент пытается подключиться через порт TCP, но не может это сделать. Вот некоторые из возможных причин, почему это происходит:

    1. Клиент и Сервер, один или оба из них не находятся в сети.

    Да, возможно, что они не подключены к локальной сети, Интернету или любой другой сети.

    1. Сервер не работает.

    Вторая наиболее распространенная причина – сервер не работает. Вы можете использовать следующие сетевые команды, например, ping, чтобы проверить, работает ли сервер.

    1. Сервер работает, но не видит порт, к которому клиент пытается подключиться.

    Это еще одна распространенная причина возникновения «java.net.ConnectException: соединение отклонено», когда сервер работает, но видит другой порт. Трудно разобраться в этом случае, пока вы не проверите конфигурацию.

    1. Брандмауэр запрещает комбинацию хост-порт.

    Почти каждая корпоративная сеть защищена. Если вы подключаетесь к сети других компаний, вам нужно убедиться, что они разрешают друг другу IP-адрес и номер порта.

    1. Неверная комбинация хост-портов.

    Проверьте последнюю конфигурацию на стороне клиента и сервера, чтобы избежать исключения отказа в соединении.

    1. Неверный протокол в строке подключения.

    TCP является базовым протоколом для многих высокоуровневых протоколов, включая HTTP, RMI и другие. Нужно убедиться, что вы передаете правильный протокол, какой сервер ожидает.

    Если вам интересно узнать больше об этом, то изучите книгу по сетевым технологиям, такую ​​как Java Network Programming (4-е дополнение), написанную Гарольдом Эллиоттом Расти.

    Java Network Programming

    Простое решение состоит в том, чтобы сначала выяснить фактическую причину исключения. Здесь важнее всего подход к поиску правильной причины и решения. Как только вы узнаете реальную причину, вам, возможно, даже не потребуется вносить какие-либо существенные изменения.

    Вот несколько советов, которые могут помочь исправить ошибку java.net.ConnectException: Connection refused:

    1. Сначала попытайтесь пропинговать целевой хост, если хост способен пинговать, это означает, что клиент и сервер находятся в сети.
    2. Попробуйте подключиться к хосту и порту сервера, используя telnet. Если вы можете подключиться, значит что-то не так с вашим клиентским кодом. Кроме того, наблюдая за выводом telnet, вы узнаете, работает ли сервер или нет, или сервер отключает соединение.

    

    java.net.ConnectException: Connection refused: connect is one of the most common networking exceptions in Java. This error comes when you are working with client-server architecture and trying to make a TCP connection from the client to the server. Though this is not as cryptic as java.lang.OutOfMemoryError: Java heap space or java.lang.UnsupportedClassVersionError, it’s still a frequent problem in distributed Java applications. java.net.ConnectException: Connection refused: connect also comes in the case of RMI (Remote Method Invocation) because RMI also uses TCP-IP protocol underneath. While writing client socket code in Java, You should always provide proper handling of this exception. 


    In this Java tutorial, we will see why connection refused exception comes and how to solve java.net.ConnectException: Connection refused: connect Exception in Java. Normally, Java books like Head First Java won’t teach you much about how to deal with such exceptions, it’s simply too much to ask for a beginner’s book.  

    java.net.ConnectException: Connection refused Error – Possible reasons

    java.net.ConnectException: Connection refused: connect solution fixConnection refused is a clear case of a client trying to connect on a TCP port but not being able to succeed. Here are some of the possible reasons why java.net.ConnectException: Connection refused: connect comes:

    1) Client and Server, either or both of them are not in the network.

    Yes it’s possible that they are not connected to LAN or internet or any other network, in that case, Java will throw

    «java.net.ConnectException: Connection refused» exception on client side.

    2) Server is not running

    The second most common reason is the server is down and not running. In that case, also you will get java.net.ConnectException: Connection refused error. What I don’t like is that the message it gives, no matter what is the reason it prints the same error. By the way, you can use the following networking commands e.g. ping to check if the server is running and listening on the port.

    3) The server is running but not listening on the port, a client is trying to connect.

    This is another common cause of «java.net.ConnectException: Connection refused«, where the server is running but listening on a different port. It’s hard to figure out this case, until, you think about it and verify the configuration. If you are working on a large project and have a hierarchical configuration file, Its possible that either default configuration

    is taking place or some other settings are overriding your correct setting.

    4) Firewall is not permitted for host-port combination

    Almost every corporate network is protected by firewalls. If you are connecting to some other company network e.g. opening a FIX session to the broker, in an Electronic Trading System, then you need to raise firewall requests from both sides to ensure that they permit each other’s IP address and port number. If the firewall is not allowing

    connection then also you will receive the same java.net.ConnectException: Connection refused exception in Java application.

    5) Host Port combination is incorrect.

    This could be another reason for java.net.ConnectException: Connection refused: connect. It’s quite possible that either you are providing an incorrect host port combination or an earlier host port combination has been changed on the server-side. Check the latest configuration on both client and server-side to avoid connection refused exception.

    6) Incorrect protocol in Connection String

    TCP is the underlying protocol for many high-level protocols including HTTP, RMI, and others. While passing connection string, you need to ensure that you are passing the correct protocol, which the server is expecting e.g. if the server has exposed its service via RMI then the connection string should begin with rmi://

    If you are curious to learn more and don’t mind researching much, then checking on some networking and Java performance courses to start with. 

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

    How to solve java.net.ConnectException: Connection refused

    The simple solution is to find out the actual reason of java.net.ConnectException: Connection refused, Possibly one of the reasons mentioned above, and solve that. What is most important here is the approach of finding correct cause and solution. Here are some tips which may help you to identify real cause of  java.net.ConnectException: Connection refused:

    1) First try to ping the destination host, if the host is ping-able it means the client and server machine are in the network.

    2) Try connecting to server host and port using telnet. If you are able to connect means something is wrong with your client code. Also, by observing telnet output you will come to know whether the server is running or not or the server is disconnecting the connection.

    That’s all on What is java.net.ConnectException: Connection refused: connect error in Java and how to fix it. As I said there is no definite reason for this error and could be many things that can go wrong. Thankfully, this is more to do with configuration or environment and once you find out the real cause, you might not even need to make any change on your side.

    Related Java debugging tutorials for Java programmers

    Java Connection Refused

    How to solve java.net.ConnectException: Connection refused

    The simple solution is to find out the actual reason of java.net.ConnectException: Connection refused, Possibly one of the reasons mentioned above, and solve that. What is most important here is the approach of finding correct cause and solution. Here are some tips which may help you to identify real cause of  java.net.ConnectException: Connection refused:

    1) First try to ping the destination host, if the host is ping-able it means the client and server machine are in the network.

    2) Try connecting to server host and port using telnet. If you are able to connect means something is wrong with your client code. Also, by observing telnet output you will come to know whether the server is running or not or the server is disconnecting the connection.

    That’s all on What is java.net.ConnectException: Connection refused: connect error in Java and how to fix it. As I said there is no definite reason for this error and could be many things that can go wrong. Thankfully, this is more to do with configuration or environment and once you find out the real cause, you might not even need to make any change on your side.

    Related Java debugging tutorials for Java programmers

    java.net.ConnectException: Connection refused is a common exception if you are dealing with network operations in Java. This error indicates that you are trying to connect to a remote address and connection is refused remotely. It’s possible if there is no remote process/service listening at the specified address or port.

    You might see one of the following error lines in your stack trace when you get Connection refused exception.

      java.net.ConnectException: Connection refused: connect
      at java.net.DualStackPlainSocketImpl.connect0(Native Method)
      at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
      at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
      at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
      at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
      at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
      at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
      at java.net.Socket.connect(Socket.java:579)
      at java.net.Socket.connect(Socket.java:528)
    
      java.net.ConnectException: Connection refused: 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:520)
      at java.net.Socket.connect(Socket.java:470)
    

    java.net.ConnectException: Connection refused exception clearly indicates that the program you are executing is trying to connect to server side but a successful connection cannot be established.

    Possible Causes of java.net.ConnectException: Connection refused

    1. Client is trying to connect wrong IP or port: This is a common reason when you get ConnectException. Sometimes applications running on the server side allocate different ports each time they are started. You can either configure the application on the server side, so that it uses fixed port, or you can change the client application, so that it connects to correct port.

    2. Server is not running: This is also a possible reason for java.net.ConnectException.
    You should check whether the server is open or not. It might be a database server, an application server or a custom server you have implemented. If you try to open a socket connection to a closed server, you will get a connection exception.

    3. Server is open but it is not listening connections: This might be the case, for instance, when application server is up and running but an installed application is not started correctly. You should check admin console of your server to check the status of applications on the server. Sometimes application is started correctly but it isn’t listening the port, you are trying to connect.

    4. Firewall is blocking connections to remote host: Firewall might be the problem if you cannot connect to server side. If a firewall is blocking connections to server, client application cannot open connection on the specified IP and port.

    1. Check IP address and port: First step to resolve java.net.ConnectException is checking IP address and port. If IP address and port are correct, then you should follow the other steps below.

    2. Ping the server IP address: You can use ping tool to test whether you can connect to server or not.

    A successful ping response is as follows:

    C:>ping 192.168.1.1
    
    Pinging 192.168.1.1 with 32 bytes of data:
    Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
    Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
    Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
    Reply from 192.168.1.1: bytes=32 time=1ms TTL=64
    
    Ping statistics for 192.168.1.1:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
         Minimum = 1ms, Maximum = 1ms, Average = 1ms

    Ping response for an unsuccessful connection is as follows:

    C:>ping 192.168.1.23
    
    Pinging 192.168.1.23 with 32 bytes of data:
    Reply from 192.168.1.23: Destination host unreachable.
    Reply from 192.168.1.23: Destination host unreachable.
    Reply from 192.168.1.23: Destination host unreachable.
    Reply from 192.168.1.23: Destination host unreachable.
    
    Ping statistics for 192.168.1.23:
         Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

    3. Try connecting the server with Telnet: You can use telnet application to simulate connection to the server. To use telnet type telnet {Server IP address} {Server port} on the command prompt. If telnet responds “Could not open connection to the host”, then you should investigate further for problems. Maybe, server is not running, or there might be a firewall issue.

    C:>telnet 127.0.0.1 8080
    Connecting To 127.0.0.1...Could not open connection to the host, on port 8080: Connect failed

    Понравилась статья? Поделить с друзьями:
  • Ошибка java lang nullpointerexception в программе
  • Ошибка java lang illegalargumentexception как исправить
  • Ошибка java io ioexception stalcraft
  • Ошибка java io ioexception cannot run program
  • Ошибка invalid access token что это