I am connecting to Geth using Web3j plugin.

web3j = Web3j.build(new HttpService("http://<ip>:<port>")); // defaults to http://localhost:8545/

However, if the Geth node is not started, I need to throw an exception. How can I find if the Geth node is started or no using web3j java code ?

try {
    Web3j web3j = Web3j.build(new HttpService("LINK-TO-YOUR-NODE"));
    // this will cause the exception if web3j is not connected
    LOG.info("Connected to Ethereum client version: "
        + web3j.web3ClientVersion().send().getWeb3ClientVersion());
} catch (Exception e) {
    LOG.error("WEB3-Connection Error", e);

The answer of TLHBM is also correct

| improve this answer | |

this code is getting blockchain chain ID(version)

we can use this kind of code for checking a connection

from this

| improve this answer | |

RPC net_listening is available to check if provider is available (specifically over IPC where connection does not mean that RPC is available).


Web3j exposes this as netListening method.

web3j = Web3j.build(new HttpService("http://<ip>:<port>"));
if(web3j.netListening() ){
//Do rest of operations 
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.