Timeout error in all my apps for every call to smtp servers

On my VPS (a tophost.it "TopServer" with Ubuntu 12.04 LTS), since a few days ago all my apps are became unable to send emails. All I could learn from the logs is that every request goes timeout.

I then tried to simply call from terminal telnet smtp.gmail.com 587 and I noticed the following anomaly: while on every other well-working server the answer takes only few ms to process and is simply

Trying 173.194.65.109...
Connected to gmail-smtp-msa.l.google.com.

On the VPS in question the answer is instead

Trying 2a00:1450:4013:c01::6c...

..and only after approximately one minute (during which the apps are going to timeout I guess)...it finally says:

Trying 74.125.136.108...
Connected to smtp.gmail.com.

So what's going on here? Why it tries with an IPv6 before and, only after several seconds, with the correct IPv4? How can I fix this behavior to avoid the timeout errors?


Solution 1:

I found a temporary fix disabling IPv6. What I did was adding the following lines to /etc/sysctl.conf:

#disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1

Then either restart or instruct sysctl to reload. Now the apps are able to send emails again, and with no initial delay.

You can always know if IPv6 is enabled by running

cat /proc/sys/net/ipv6/conf/all/disable_ipv6

from terminal. Two possible answers: 0 => IPv6 is enabled; 1 => IPv6 disabled.

At least, while I wait for the service provider to fix the issue, I learnt something new.

Solution 2:

(Shamelessly copied from https://stackoverflow.com/a/29939735/32453)

You can configure Ubuntu to prefer IPv4 over IPv6. This way you will be able to send emails and access IPv6-only sites. Edit /etc/gai.conf and uncomment the following line:

precedence ::ffff:0:0/96 100