when I try to load a web page to terminal it gives curl: (6) Could not resolve host error.
I have internet in my PC and trying from my home internet connection. So as I there is no any proxy involve here.
[root@localhost kevin]# curl http://google.com
curl: (6) Could not resolve host: google.com; Name or service not known
clean all and tried again but no lucky.
But if I use IP instead of the domain name, it works fine.
[root@localhost kevin]# curl http://173.194.46.0
any clue please?
![]()
Sathish
3,6901 gold badge16 silver badges27 bronze badges
asked Jul 26, 2014 at 5:26
![]()
Nayana AdassuriyaNayana Adassuriya
22.9k28 gold badges103 silver badges145 bronze badges
5
Issues were:
- IPV6 enabled
- Wrong DNS server
Here is how I fixed it:
IPV6 Disabling
- Open Terminal
- Type
suand enter to log in as the super user - Enter the root password
- Type
cd /etc/modprobe.d/to change directory to/etc/modprobe.d/ - Type
vi disableipv6.confto create a new file there - Press
Esc + ito insert data to file - Type
install ipv6 /bin/trueon the file to avoid loading IPV6 related modules - Type
Esc + :and thenwqfor save and exit - Type
rebootto restart fedora - After reboot open terminal and type
lsmod | grep ipv6 - If no result, it means you properly disabled IPV6
Add Google DNS server
- Open Terminal
- Type
suand enter to log in as the super user - Enter the root password
- Type
cat /etc/resolv.confto check what DNS server your Fedora using. Mostly this will be your Modem IP address. - Now we have to Find a powerful DNS server. Luckily there is a open DNS server maintain by Google.
- Go to this page and find out what are the «Google Public DNS IP addresses»
- Today those are
8.8.8.8and8.8.4.4. But in future those may change. - Type
vi /etc/resolv.confto edit theresolv.conffile - Press
Esc + ifor insert data to file - Comment all the things in the file by inserting # at the begin of the each line. Do not delete anything because can be useful in future.
-
Type below two lines in the file
nameserver 8.8.8.8
nameserver 8.8.4.4-Type
Esc + :and thenwqfor save and exit - Now you are done and everything works fine (Not necessary to restart).
- But every time when you restart the computer your /etc/resolv.conf will be replaced by default. So I’ll let you find a way to avoid that.
Here is my blog post about this:
http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html
![]()
answered Jul 28, 2014 at 1:29
![]()
Nayana AdassuriyaNayana Adassuriya
22.9k28 gold badges103 silver badges145 bronze badges
4
Perhaps you have some very weird and restrictive SELinux rules in place?
If not, try strace -o /tmp/wtf -fF curl -v google.com and try to spot from /tmp/wtf output file what’s going on.
answered Jul 26, 2014 at 11:12
![]()
5
I have today similar problem. But weirder.
- host — works
host pl.archive.ubuntu.com - dig — works on default and on all other DNS’s
dig pl.archive.ubuntu.com,dig @127.0.1.1 pl.archive.ubuntu.com - curl — doesn’t work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
* Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com
Revelation
Eventually I used strace on curl and found that it was connection to nscd deamon.
connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0
Solution
I’ve restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!
systemctl restart nscd.service
answered Jun 29, 2017 at 11:29
3
There is no need to disable IPv6 as the answer suggests. The reason curl fails is simply because the DNS resolution is missing.
There is one liner solution to this.
If you care about what is inside /etc/resolv.conf then append it:
echo 'nameserver 1.1.1.1' | sudo tee -a /etc/resolv.conf >/dev/null
I usually don’t care and just replace the content of the file:
echo 'nameserver 1.1.1.1' | sudo tee /etc/resolv.conf >/dev/null
answered Oct 11, 2021 at 17:33
HoumanHouman
63.1k86 gold badges266 silver badges454 bronze badges
0
Try nslookup google.com to determine if there’s a DNS issue.
192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well?
What happens when you try ping google.com. Can you browse to it on a Internet web browser?
answered Jul 26, 2014 at 13:25
2
In Our case, the command was passed through mail/skype and the person who needs to execute copied an extra space.
we found that extra space after an hour and removing that made it work.
answered Aug 6, 2022 at 3:20
nikhil2000nikhil2000
1493 silver badges13 bronze badges
I had an issue with IPV6 that suddenly showed up in wordpress admin where curl failed to connect to wordpress.org etc giving
An unexpected error occurred. Something may be wrong with WordPress.org
and also
Installation failed: Download failed. cURL error 28: Resolving timed out after 10005 milliseconds
I eventually sorted by adding the following as a php file in mu-plugins:
add_action( 'http_api_curl', function( $curl_handle ) { curl_setopt( $curl_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );});
and also when using curl directly in php by using the following option in the options array:
curl_setopt_array($curl, array(CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4));
The OS is IBM i (OS400/i5OS) v7.2 running on Power 6 and the php version is 8.1.10. Interestingly IPV6 is not active on the box.
answered Sep 17, 2022 at 11:37
Basically copying this over from https://stackoverflow.com/questions/54771917/could-not-resolve-host-error-with-curl-multi-on-curl-version-7-64
I’m not the author of the StackOverflow question, but I have the exact same issue.
I did this
php script:
<?php
$url = "https://www.example.com";
$options = array(
CURLOPT_RETURNTRANSFER => true, // don't echo page
CURLOPT_VERBOSE =>true,
);
$cm = curl_multi_init();
// step 1 of 3 (adding requests)
//request 1
$ch1 = curl_init( $url );
$verboseH1 = fopen('php://temp', 'w+');
$options[CURLOPT_STDERR] = $verboseH1;
curl_setopt_array( $ch1, $options);
curl_multi_add_handle($cm, $ch1);
//request 2
$ch2 = curl_init( $url );
$verboseH2 = fopen('php://temp', 'w+');
$options[CURLOPT_STDERR] = $verboseH2;
curl_setopt_array( $ch2, $options);
curl_multi_add_handle($cm, $ch2);
//request 3
$ch3 = curl_init( $url );
$verboseH3 = fopen('php://temp', 'w+');
$options[CURLOPT_STDERR] = $verboseH3;
curl_setopt_array( $ch3, $options);
curl_multi_add_handle($cm, $ch3);
// step 2 of 3 (executing requests in parallel)
// for more information about these strange loops , check http://php.net/manual/en/function.curl-multi-init.php#115055
$active = null;
do {
$mrc = curl_multi_exec($cm, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($cm) == -1) {
usleep(100);
}
do {
$mrc = curl_multi_exec($cm, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
// step 3 of 3 (getting results)
echo "<h1>Requet 1</h1>n";
echo "errmsg1: '" . curl_error($ch1) . "'n";
rewind($verboseH1);
echo "verbose1:n" . stream_get_contents( $verboseH1) . "n";
echo "===============================================================n";
echo "<h1>Requet 2</h1>n";
echo "errmsg2: '" . curl_error($ch2) . "'n";
rewind($verboseH2);
echo "verbose2:n" . stream_get_contents( $verboseH2) . "n";
echo "===============================================================n";
echo "<h1>Requet 3</h1>n";
echo "errmsg3: '" . curl_error($ch3) . "'n";
rewind($verboseH3);
echo "verbose3:n" . stream_get_contents( $verboseH3) . "n";
exit;
output:
<h1>Requet 1</h1>
errmsg1: ''
verbose1:
* Expire in 0 ms for 6 (transfer 0x2b750f0)
* Expire in 1 ms for 1 (transfer 0x2b750f0)
* Expire in 0 ms for 1 (transfer 0x2b750f0)
* Expire in 0 ms for 1 (transfer 0x2b750f0)
* Trying 93.184.216.34...
* TCP_NODELAY set
* Expire in 149999 ms for 3 (transfer 0x2b750f0)
* Expire in 200 ms for 4 (transfer 0x2b750f0)
* Connected to www.example.com (93.184.216.34) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: C=US; ST=California; L=Los Angeles; O=Internet Corporation for Assigned Names and Numbers; OU=Technology; CN=www.example.org
* start date: Nov 28 00:00:00 2018 GMT
* expire date: Dec 2 12:00:00 2020 GMT
* subjectAltName: host "www.example.com" matched cert's "www.example.com"
* issuer: C=US; O=DigiCert Inc; CN=DigiCert SHA2 Secure Server CA
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x2b750f0)
> GET / HTTP/2
Host: www.example.com
Accept: */*
* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
< HTTP/2 200
< cache-control: max-age=604800
< content-type: text/html; charset=UTF-8
< date: Tue, 19 Feb 2019 17:01:16 GMT
< etag: "1541025663+ident"
< expires: Tue, 26 Feb 2019 17:01:16 GMT
< last-modified: Fri, 09 Aug 2013 23:54:35 GMT
< server: ECS (dfw/27B2)
< vary: Accept-Encoding
< x-cache: HIT
< content-length: 1270
<
* Connection #0 to host www.example.com left intact
===============================================================
<h1>Requet 2</h1>
errmsg2: 'Could not resolve host: www.example.com'
verbose2:
* Expire in 0 ms for 6 (transfer 0x2b7a9a0)
* Found bundle for host www.example.com: 0x2b86800 [serially]
* Server doesn't support multi-use (yet)
* Expire in 1 ms for 1 (transfer 0x2b7a9a0)
* Expire in 0 ms for 1 (transfer 0x2b7a9a0)
* Hostname 'www.example.com' was found in DNS cache
* Expire in 0 ms for 1 (transfer 0x2b7a9a0)
* Trying 93.184.216.34...
* TCP_NODELAY set
* Expire in 149999 ms for 3 (transfer 0x2b7a9a0)
* Expire in 200 ms for 4 (transfer 0x2b7a9a0)
* Connected to www.example.com (93.184.216.34) port 443 (#1)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: C=US; ST=California; L=Los Angeles; O=Internet Corporation for Assigned Names and Numbers; OU=Technology; CN=www.example.org
* start date: Nov 28 00:00:00 2018 GMT
* expire date: Dec 2 12:00:00 2020 GMT
* subjectAltName: host "www.example.com" matched cert's "www.example.com"
* issuer: C=US; O=DigiCert Inc; CN=DigiCert SHA2 Secure Server CA
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x2b7a9a0)
> GET / HTTP/2
Host: www.example.com
Accept: */*
* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
< HTTP/2 200
< cache-control: max-age=604800
< content-type: text/html; charset=UTF-8
< date: Tue, 19 Feb 2019 17:01:16 GMT
< etag: "1541025663+ident"
< expires: Tue, 26 Feb 2019 17:01:16 GMT
< last-modified: Fri, 09 Aug 2013 23:54:35 GMT
< server: ECS (dfw/562D)
< vary: Accept-Encoding
< x-cache: HIT
< content-length: 1270
<
* Could not resolve host: www.example.com
* Closing connection 1
===============================================================
<h1>Requet 3</h1>
errmsg3: 'Could not resolve host: www.example.com'
verbose3:
* Expire in 0 ms for 6 (transfer 0x2b80250)
* Found bundle for host www.example.com: 0x2b86800 [serially]
* Server doesn't support multi-use (yet)
* Expire in 1 ms for 1 (transfer 0x2b80250)
* Expire in 0 ms for 1 (transfer 0x2b80250)
* Hostname 'www.example.com' was found in DNS cache
* Expire in 0 ms for 1 (transfer 0x2b80250)
* Trying 93.184.216.34...
* TCP_NODELAY set
* Expire in 150000 ms for 3 (transfer 0x2b80250)
* Expire in 200 ms for 4 (transfer 0x2b80250)
* Connected to www.example.com (93.184.216.34) port 443 (#2)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server accepted to use h2
* Server certificate:
* subject: C=US; ST=California; L=Los Angeles; O=Internet Corporation for Assigned Names and Numbers; OU=Technology; CN=www.example.org
* start date: Nov 28 00:00:00 2018 GMT
* expire date: Dec 2 12:00:00 2020 GMT
* subjectAltName: host "www.example.com" matched cert's "www.example.com"
* issuer: C=US; O=DigiCert Inc; CN=DigiCert SHA2 Secure Server CA
* SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x2b80250)
> GET / HTTP/2
Host: www.example.com
Accept: */*
* Connection state changed (MAX_CONCURRENT_STREAMS == 100)!
< HTTP/2 200
< accept-ranges: bytes
< cache-control: max-age=604800
< content-type: text/html; charset=UTF-8
< date: Tue, 19 Feb 2019 17:01:16 GMT
< etag: "1541025663"
< expires: Tue, 26 Feb 2019 17:01:16 GMT
< last-modified: Fri, 09 Aug 2013 23:54:35 GMT
< server: ECS (dfw/F4AA)
< vary: Accept-Encoding
< x-cache: HIT
< content-length: 1270
<
* Could not resolve host: www.example.com
* Closing connection 2
Reproduce:
This will upgrade curl to 7.64.0 which has the issue:
docker pull php:7.2-alpine
docker run --rm -it php:7.2-alpine sh
apk upgrade curl
curl https://gist.githubusercontent.com/Schnitzel/ed65648571f25647eb0bc7b2e5a1b998/raw/6876ce533e6085656fac039492027c98372f27bf/test.php > test.php
php test.php
I expected the following
This will keep curl on 7.63.0 which does not have the issue
docker pull php:7.2-alpine
docker run --rm -it php:7.2-alpine sh
curl https://gist.githubusercontent.com/Schnitzel/ed65648571f25647eb0bc7b2e5a1b998/raw/6876ce533e6085656fac039492027c98372f27bf/test.php > test.php
php test.php
curl/libcurl version
$ curl --version
curl 7.64.0 (x86_64-alpine-linux-musl) libcurl/7.64.0 OpenSSL/1.1.1a zlib/1.2.11 libssh2/1.8.0 nghttp2/1.35.1
Release-Date: 2019-02-06
Protocols: dict file ftp ftps gopher http https imap imaps pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP HTTP2 UnixSockets HTTPS-proxy
operating system
cat /etc/alpine-release
3.9.0
Could this maybe have to do with #3446 ?
I have a CentOS 7.3 machine that is a guest running on Oracle VirtualBox. The host is a Windows machine. I can ping 8.8.8.8 from the Linux server. The Linux server can ping itself by its hostname ping coolvm. As root I recently did a yum -y update command. That is when curl stopped working. FQDNs will not resolve.
If I try this:
curl -v http://www.google.com
I get this error:
- Could not resolve host: www.google.com; Unknown error
- Closing connection 0 curl: (6) COuld not resolve host: www.google.com; Unknown error
The commands nslookup, dig and host have not been installed. I cannot install new Yum packages because I get an error related to host resolution («Resolving time out»).
The /etc/resolv.conf file looks like this:
# Generated by NetworkManager
search localdomain
nameserver 8.8.8.8
nameserver 8.8.4.4
I tried rebooting the host machine (and thus the guest too). But that did not help me. Browsing the internet has not changed.
The interface for the main NIC in /etc/sysconfig/network-scripts/ has DNS server stanzas that have worked in the past. The interface file is standard and complete. I have not changed it since the yum -y update command.
How can I get FQDNs to resolve? I want to use the Lynx command. My repositories rely on FQDNs to resolve. I cannot use yum to install packages.
Update. I ran this command:
cat /etc/nsswitch.conf | grep -i hosts
I saw this:
#hosts: db files nisplus nis dns
hosts: files dns myhostname
Буквально пару дней назад переносили сайт на WordPress на обновленный сервер, и столкнулись с проблемой установки обновлений и новых плагинов. Если поискать в интернете, видно, что люди часто сталкиваются с такой ошибкой и предлагается всего 2 варианта решения:
- Подождите, может, само рассосется
- Обратитесь к системному администратору
Ждать — не вариант. Если вы используете виртуальный хостинг одного из хостеров, то техподдержка должна решить эту проблему достаточно быстро. А если вы арендовали VPS и сами себе администратор, то информация ниже поможет вам решить проблему.
Как проявляется ошибка
Ошибка возникает при попытке установить обновление WordPress, обновить темы оформления или установить новый плагин. При этом появляется сообщение «Warning: Произошла непредвиденная ошибка. Возможно, что-то не так с сайтом WordPress.org или с настройками вашего сервера. Если проблема не решится, обратитесь на форумы поддержки. (Не удалось установить защищённое соединение с WordPress.org. Пожалуйста, свяжитесь с администратором сервера)».
В логах сервера фигурируют следующие файлы, в которых возникает ошибка:
/wp-admin/includes/plugin-install.php
/wp-admin/includes/translation-install.php
/wp-admin/includes/update.php
/wp-includes/update.php
Если у вас установлен плагин Health Check & Troubleshooting (кстати, настоятельно рекомендую его установить), то в отчете можно увидеть ошибки вида
cURL error 6: Could not resolve host: api.wordpress.org
Очевидно, что проблема в библиотеке cURL, либо настройках сервера.
Как решить проблему
Нам понадобится доступ к серверу по протоколу SSH и права администратора для внесения изменений в настройки и установки ряда библиотек.
1. Проверяем настройки в файле php.ini
Обычно этот файл находится в папке /etc/php.ini или /etc/php/<версия php>/apache2/php.ini. Убедитесь, что эти две настройки включены:
allow_url_fopen = On
allow_url_include = On
2. Проверяем установку необходимых библиотек с помощью phpinfo()
Создайте на своем сервере файл pi.php в корне сайта со следующим содержимым:
<?php
phpinfo();
Откройте файл в браузере http://<адрес сервера>/pi.php и проверьте, что следующие библиотеки установлены в Enabled
OpenSSL
Socket
3. Проверяем файл resolv.conf
Файл можно найти по адресу /etc/resolv.conf — воспользуйтесь привычным текстовым редактором. Удалите из файла все комментарии, укажите используемые DNS-сервера (рекомендую Google, но вы можете выбрать те, которые нравятся):
nameserver 8.8.8.8
nameserver 8.8.4.4
Сохраните изменения и закройте редактор. Убедитесь, что файл доступен для всех пользователей:
chmod a+r /etc/resolv.conf
4. Если вы используете высокоэффективную связку nginx + php-fpm
Для начала проверяем конфигурацию php-fpm для вашего сайта. Ее можно найти в /etc/php-fpm.d/<имя сайта>.conf. Откройте файл и найдите строку
chroot = <путь к песочнице>
Если строка присутствует и не закомментирована, значит php-fpm работает в режиме chroot, и вам потребуется скопировать часть файлов системы в chroot-окружение, т.к. у php-fpm нет к ним доступа. Для этого переходим в папку, указанную в chroot и выполняем следующие команды:
mkdir etc
mkdir lib64
mkdir usr
mkdir usr/share
cp -p /etc/hosts etc/
cp -p /etc/localtime etc/
cp -p /etc/resolv.conf etc/
cp -p /lib64/libss_dns* lib64/
cp -Rp /usr/share/zoneinfo usr/share/
После выполнения указанных действий перезапускаем php-fpm, и проблема решена.
systemctl restart php-fpm
Если вам требуется сопровождение VPS/VDS-сервера или помощь с настройкой, обратитесь к нам, мы занимаемся настройкой и сопровождением серверов с 2013 года. Порекомендуем хостера, подберем конфигурацию и поможем запустить ваш проект.