How can I check the possible reason for java.net.SocketTimeoutException.
I have a program that just pings to a website. however I am getting SocketTimeoutException. I know it is happening due to timeout expiring before the connection is established. But I want to know the precise reason of the issue. Like It is to do with internal DNS failure or due to unavailability of the internet or what !
Tried searching for similar questions but I didn't get the exact reason for not being able to establish the connection.
Below code snippet explains the problem
import java.net.HttpURLConnection;
import java.net.URL;
public class URLConnectionTest {
public static void main(String[] args) {
try {
String urlString = "https://www.google.com";
URL url = new URL (urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.connect();
System.out.println("Connected !!!");
}
catch(Exception e) {
System.out.println("Error occurred while connecting" + e);
}
}
}
Now there are multiple outputs for different case.
When I turned off laptop's wifi
Error occurred while connecting java.net.UnknownHostException: www.google.com
When I connect to wifi but router doesn't have the connectivity
Error occurred while connecting java.net.SocketTimeoutException: connect timed out
Few lines of Stacktrace for Timeout
java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
I've seen all questions and answers about this problem, I've read the FAQ, tried all solutions which I've found, except writing my own one, I've turned off less secure app Gmail and so on. I've checked telnet connection, of course, tried to ping smtp.gmail.com and everything works fine. Even I've written (to be sure) small application on C# which took me 5 minutes (and this one works!). Please give me a clue how can I solve this issue. For every solution using ttl or ssl I get this stacktrace
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at com.luga.culturalpickup.UsableSendMail.sendFromGMail(UsableSendMail.java:64)
at com.luga.culturalpickup.UsableSendMail.main(UsableSendMail.java:84)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 5 more
I've disabled firewall completely.
Even I've used some wrappers around JavaMail Api to send letters and internally they were falling with this exception!
I want to send small email using java!
for exmaple, this code produce error specified above
public class GoogleTest {
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_PORT = "465";
private static final String emailMsgTxt = "Test Message Contents";
private static final String emailSubjectTxt = "A test from gmail";
private static final String emailFromAddress = "mail4#gmail.com";
private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
private static final String[] sendTo = { "alex.95#mail.ru" };
public static void main(String args[]) throws Exception {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully mail to All Users");
}
public void sendSSLMessage(String recipients[], String subject,
String message, String from) throws MessagingException {
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.port", SMTP_PORT);
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mail4#gmail.com", "password");
}
});
session.setDebug(debug);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}
}
I get following stacktrace
DEBUG: JavaMail version 1.6.2
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: setDebug: JavaMail version 1.6.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL true
Exception in thread "main" com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:267)
at javax.mail.Transport.send0(Transport.java:252)
at javax.mail.Transport.send(Transport.java:174)
at com.luga.culturalpickup.GoogleTest.sendSSLMessage(GoogleTest.java:72)
at com.luga.culturalpickup.GoogleTest.main(GoogleTest.java:29)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:217)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
... 8 more
The configuration details look OK to me.
The big clue is that you are getting "Connection refused". In theory, there are a few possible explanations for this:
The smtp.gmail.com servers are all down. This is highly unlikely.
The smtp.gmail.com servers may have black-listed your IP address or a network range containing your IP address. (Perhaps the gmail.com servers have been getting too much SPAM via your ISP.)
Maybe there is a country-wide block on emails. (For example, it has been claimed that China does this sometimes.)
Maybe ISP is blocking the connection to smtp.gmail.com on those ports ... or maybe all outbound connections on this ports. This may be done to prevent spamming by your ISP's customers. Check your ISP's terms and conditions regarding sending emails, and check for information on how you should do it.
Maybe your organization is blocking the connection to smtp.gmail.com. This could be done so that they can monitor all out-going emails. It could also be done to prevent spamming or behavior that could be interpreted as spamming. Check with your local IT and network managers.
Maybe it is your machine's internal firewall. (Though you say that you disabled it ...)
There is one simple test you can do to validate this. Use the "telnet" command to try to connect to smtp.gmail.com on those two ports. If you get a "Connection refused", it is strong evidence of some kind of blocking somewhere.
Finally, if the ports appear to be open, check what you are doing against this tutorial page:
https://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
After one and a half of day I've found a problem. It was due to avg antivirus or to say it more correctly avg virus. It was turned off (as he has displayed me), but I've noticed some avg advertisment attached to messages sent with application written on C#, I've found a way to definitely turn it off. And it works now!
This question already has answers here:
What is a connection timeout during a http request
(2 answers)
Closed 27 days ago.
I get an exception when I run this code. Why?
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class MainClass {
public static void main(String[] args) throws Exception {
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
URL url = new URL("https://www.verisign.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
}
Exception:
Exception in thread "main" java.net.ConnectException: Connection timed out: 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.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:550)
at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl.getInputStream(HttpsURLConnectionOldImpl.java:204)
at java.net.URL.openStream(URL.java:1010)
at https.ssl.MainClass.main(MainClass.java:13)
We can't diagnose your networks for you. You need to do it yourself, or get your local admins to look at.
Things you should check before you bug your admins:
can you ping the host?
can you connect to http://www.verisign.com using a web browser?
can you connect to https://www.verisign.com using a web browser?
can you connect to http://www.verisign.com using your program?
can you connect to anything using your program?
The chances are that your problem is firewall related. My first guess would be that you don't have the correct environment variables or Java system properties set to tell the JVM to use a local proxy server for outgoing HTTP / HTTPS requests.
If it is not a problem with your settings, you will need to get help from someone local who can help you diagnose the problem.
I'm following the user guides for Apache's LDAP Client API to connect to the ApacheDS LDAPS server. But it will not connect. I have tried everything. I'm able to connect to the LDAP server. The user guide isn't really helpful because they leave out some functions that are used in the examples. I'm using a generated certificate by ApacheDS.
import static org.junit.Assert.assertTrue;
import org.apache.directory.api.util.Network;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.NoVerificationTrustManager;
public class SecureP2P {
public static void main(String[] args) throws Exception {
LdapConnectionConfig sslConfig = new LdapConnectionConfig();
sslConfig.setLdapHost(Network.LOOPBACK_HOSTNAME);
sslConfig.setUseSsl(true);
sslConfig.setLdapPort(10636);
sslConfig.setSslProtocol("SSLv3");
sslConfig.setTrustManagers(new NoVerificationTrustManager());
try (LdapConnection connection = new LdapNetworkConnection(sslConfig)) {
connection.bind("uid=admin,ou=system", "secret");
assertTrue(((LdapNetworkConnection) connection).getConfig().isUseSsl());
assertTrue(connection.isAuthenticated());
}
}
}
Here is the error in the log files of the ApacheDS Server:
WARN [org.apache.mina.util.DefaultExceptionMonitor] - Unexpected exception.
org.apache.mina.core.filterchain.IoFilterLifeCycleException: onPreAdd(): sslFilter:SslFilter in (0x00000007: nio socket, server, /192.168.1.249:65465 => /192.168.1.249:10636)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:383)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.addLast(DefaultIoFilterChain.java:189)
at org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder.buildFilterChain(DefaultIoFilterChainBuilder.java:496)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.addNow(AbstractPollingIoProcessor.java:504)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.handleNewSessions(AbstractPollingIoProcessor.java:479)
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:68)
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1088)
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at sun.security.ssl.Handshaker.activate(Handshaker.java:503)
at sun.security.ssl.SSLEngineImpl.kickstartHandshake(SSLEngineImpl.java:729)
at sun.security.ssl.SSLEngineImpl.beginHandshake(SSLEngineImpl.java:756)
at org.apache.mina.filter.ssl.SslHandler.init(SslHandler.java:185)
at org.apache.mina.filter.ssl.SslFilter.onPreAdd(SslFilter.java:438)
at org.apache.mina.core.filterchain.DefaultIoFilterChain.register(DefaultIoFilterChain.java:381)
... 10 more
Error message when running the client:
Exception in thread "main" org.apache.directory.ldap.client.api.exception.InvalidConnectionException: An established connection was aborted by the software in your host machine
at org.apache.directory.ldap.client.api.LdapNetworkConnection.writeRequest(LdapNetworkConnection.java:4190)
at org.apache.directory.ldap.client.api.LdapNetworkConnection.bindAsync(LdapNetworkConnection.java:1314)
at org.apache.directory.ldap.client.api.LdapNetworkConnection.bind(LdapNetworkConnection.java:1212)
at org.apache.directory.ldap.client.api.AbstractLdapConnection.bind(AbstractLdapConnection.java:127)
at org.apache.directory.ldap.client.api.AbstractLdapConnection.bind(AbstractLdapConnection.java:112)
at edu.fau.SecureP2P.main(SecureP2P.java:22)
In this post java H2 hanging on getLocalhost on arm32 device I had a problem creating database using Hibernate. I have now managed to remove track down the issue to core java with this test program, InetAddress lookup using getByName("localhost") works, but getLocalHost() fails !
Points towards configuration issue with linux machine. localhost is in /etc/hosts
But I am no Linux expert, what could cause this ?
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Addresses
{
public static void main(String[] args) {
try {
InetAddress address= InetAddress.getByName("localhost");
System.out.println(address.getHostName()+ "-"+address.getHostAddress());
address= InetAddress.getLocalHost();
System.out.println(address.getHostName()+ "-"+address.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
Gives
localhost-127.0.0.1
java.net.UnknownHostException: N1-ZS10: N1-ZS10: Name or service not known
at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
at Addresses.main(Addresses.java:12)
Caused by: java.net.UnknownHostException: N1-ZS10: Name or service not known
at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
... 1 more