Ошибка php network getaddresses

You cannot open a connection directly to a path on a remote host using fsockopen. The url www.mydomain.net/1/file.php contains a path, when the only valid value for that first parameter is the host, www.mydomain.net.

If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.

If you only want to send an HTTP request and ignore the response, you could use fsockopen() and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen(), it might look something like this:

$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1n");
fputs($fp, "Host: www.mydomain.netn");
fputs($fp, "Connection: closenn"); 

That leaves any error handling up to you of course, but it would mean that you wouldn’t waste time reading the response.

im working on a website which mostly uses the database. the problem is that im geting the following error: mysqli_connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known
I cant figure out how to fix it. I’ve penta-checked the connect and it seems to be okay.

function connect($hostname, $username, $password, $database)
{
    $conid = mysqli_connect($hostname, $username, $password, TRUE);


    if($conid == FALSE)
    {
        if(DEBUG == TRUE)
        {
            show_error("MySQL Connection using `$hostname`, `$username`, `$password` was refused");
        }

        return;
    }

    else
    {
        $dbid = mysqli_select_db($database, $conid);

        if($dbid == FALSE)
        {
            if(DEBUG == TRUE)
            {
                show_error("MySQL could not connect to database `$database`");
            }

            return;
        }

        else
        {
            self::$connections[] = $conid;
            self::$connection    = $conid;
        }
    }
}

The code is writen in 2010 and then somehow it worked. Is it possible to fixit?

asked Apr 8, 2014 at 19:47

Your PHP server upgraded and your hosting didn’t support it.

justisb's user avatar

justisb

7,0012 gold badges26 silver badges44 bronze badges

answered Jul 29, 2015 at 1:19

user5167284's user avatar

1

I had a similar issue, My Issue was resolved by checking and resolving DNS resolution (in our case, the use in cagefs had different /etc/hosts than the core system)

answered Sep 8, 2015 at 12:59

Jacob Evans's user avatar

Jacob EvansJacob Evans

3232 silver badges16 bronze badges

Just came across the error myself between 2 working PHP 7.1, Apache 2.4 & mariaDB 10.2/10.4 servers.

The issue for me was caused by using «http://1.2.3.4/» as the Database Host — this will cause PHP to return this error mysqli_connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known. For me this was of course some bogus error for me as they are both individually hosting the same websites & databases so there was no reason for it not to work.

The host variable should only be the IP address «1.2.3.4» or domain/subdomain (excluding the protocol) «example.com» or «subdomain.example.com» — which now connects correctly.

answered Mar 29, 2020 at 19:41

Bim's user avatar

BimBim

4314 silver badges5 bronze badges

@pizsd

Description:

mysql, redis This problem occurs under the debug of phpstorm. This problem does not occur directly in the browser or postman. I want to know what causes it.

error

redis
php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://reids:6379]
mysql
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

Project configuration file .env
redis

REDIS_HOST=reids
REDIS_PASSWORD=null
REDIS_PORT=6379

mysql

DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=campaign
DB_USERNAME=root
DB_PASSWORD=root

docker fo mac
dcoker:19.03
docker-compsoe:1.25.2

@bestlong

check container working first.
docker-compse ps
docker-compse logs mysql
docker-compse logs redis

Ref #2507

@metalcamp

Probably typo:

REDIS_HOST=reids

@pizsd

@metalcamp Not the problem, the configuration is wrong

@metalcamp

@pizsd: Is your redis service (in docker-compose.yml) also named reids?

@bestlong

@ugurdnlr

I’m getting this error too.

IlluminateDatabaseQueryException : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

when i run tests from phpstorm I’m getting this. But i didn’t get this when i run from terminal like phpunit TestsExampleTest

My project .env

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=default
DB_USERNAME=default
DB_PASSWORD=secret

laradock .env

MYSQL_VERSION=5.7
MYSQL_DATABASE=default
MYSQL_USER=default
MYSQL_PASSWORD=secret
MYSQL_PORT=3306

docker-compose.yml

mysql:
      build:
        context: ./mysql
        args:
          - MYSQL_VERSION=${MYSQL_VERSION}
      environment:
        - MYSQL_DATABASE=${MYSQL_DATABASE}
        - MYSQL_USER=${MYSQL_USER}
        - MYSQL_PASSWORD=${MYSQL_PASSWORD}
        - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
        - TZ=${WORKSPACE_TIMEZONE}
      volumes:
        - ${DATA_PATH_HOST}/mysql:/var/lib/mysql
        - ${MYSQL_ENTRYPOINT_INITDB}:/docker-entrypoint-initdb.d
      ports:
        - "${MYSQL_PORT}:3306"
      networks:
        - backend

@ugurdnlr

My Solution:

PhpStorm->Preferences->Languages & Frameworks->PHP->Test Frameworks

Add PHPUnit by Remote Interpreter

Select Docker interpreter

After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)

And if you know which network is using in docker container you should write name of network ( docker network ls ) into Network Mode section then click OK . That’s it.

But if you don’t know which network is using . First you should remove all unused networks ( docker network prune ) then run ( docker network ls )

@stale

Hi 👋 this issue has been automatically marked as stale 📌 because it has not had recent activity 😴. It will be closed if no further activity occurs. Thank you for your contributions ❤️.

@stale

Hi again 👋 we would like to inform you that this issue has been automatically closed 🔒 because it had not recent activity during the stale period. We really really appreciate your contributions, and looking forward for more in the future 🎈.

@maMykola

My Solution:

PhpStorm->Preferences->Languages & Frameworks->PHP->Test Frameworks

Add PHPUnit by Remote Interpreter

Select Docker interpreter

After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)

And if you know which network is using in docker container you should write name of network ( docker network ls ) into Network Mode section then click OK . That’s it.

But if you don’t know which network is using . First you should remove all unused networks ( docker network prune ) then run ( docker network ls )

changing Network mode from bridge to docker internal network fixed my problem

@BonBonSlick

In my case error was misleading. You have to run commands from docker container eg docker-compose exec containerName (app) php (serviceName) bin/console doctrine:migrations:migrate (service command).
I was trying to run it from outside of the container. Dunno how not connected redis to doctrine is related during doctrine command, but that was the case. Lost 2-3 hours on that and asked for help other dev.

@HuyNguyen206

hi @ugurdnlr,
Regarding this section «After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)», could you explain in more detail with screenshot?
I try to config but an error occurs
This is screenshots of my config
image
image
image

Thanks in advance

@keizah7

My Solution:

PhpStorm->Preferences->Languages & Frameworks->PHP->Test Frameworks

Add PHPUnit by Remote Interpreter

Select Docker interpreter

After created you should add link ( Links section ) which one do u want to use ( mysql, redis) to docker container (click Browse in docker container section)

And if you know which network is using in docker container you should write name of network ( docker network ls ) into Network Mode section then click OK . That’s it.

But if you don’t know which network is using . First you should remove all unused networks ( docker network prune ) then run ( docker network ls )

thank you! Changed Network mode to my subnet in Docker container settings and it started working

 

Пользователь 32599

Эксперт

Сообщений: 1135
Баллов: 163
Регистрация: 07.11.2008

#1

0

15.10.2012 19:58:04

При попытке перейти на страницу обновлений вот такое сообщение:

Ошибка
Ошибка соединения с сервером обновлений: [0] php_network_getaddresses: getaddrinfo failed: Name or service not known. Нет соединения с сервером обновлений.
Не установлено соединение с сервером обновлений.

Внутри локальной сети портал доступен по адресу 192.168.0.10
Стоит Kerio Control, и с адреса 192.168.0.10 все разрешено.

Техподдержка ответила

Цитата
Тут явно проблема в настройках сервера, либо фаервола, так как в проверке сайта есть и ошибка работы с сокетами, в котором сайт не может подключиться к самому себе.

Портал висит на BitrixVM 3.1, все работает из под администратора на Windows Server 2008, интернет есть на машине. Куда копать?

Профессиональная и дорогая вёрстка.

 

Андрей Погорелый,  думаю проблема с настройками DNS на виртуальной машине, посмотрите что написано в файле /etc/resolv.conf

 

Если обновлять по частям, то всё ок

 

vi /etc/sysconfig/network

добавить:
GATEWAY=192.168.0.1

 

Пользователь 57829

Гуру

Сообщений: 3754
Баллов: 320
Регистрация: 17.02.2010

#5

0

07.05.2014 13:32:20

Цитата
Сергей Кирясов пишет:
vi /etc/sysconfig/network

добавить:
GATEWAY=192.168.0.1

т.е. вас не смущает что у кого то может быть и другой шлюз? :)

Карточка партнера Наш сайт

 

Аналогчно. Интегрирую свой интернет-магазин с CRM (демо на вирт. машине). Обновление прошло в штатном режиме, но дальше, после введения адреса своего аккаунта на Битрикс-24, логина и пароля, появляется сообщение: [0] php_network_getaddresses: getaddrinfo failed: Name or service not known

Кто виноват и что делать?

 

настраивать DNS, php не может получить информацию по доменному имени.

 

Не может ли это быть ограничением демо-версии?

 

Пользователь 57829

Гуру

Сообщений: 3754
Баллов: 320
Регистрация: 17.02.2010

#9

0

02.09.2014 10:20:17

Цитата
Владислав С. пишет:
Не может ли это быть ограничением демо-версии?

нет.

Карточка партнера Наш сайт

 

Пользователь 132775

Постоянный посетитель

Сообщений: 180
Баллов: 31
Регистрация: 11.06.2012

#10

0

23.09.2014 08:24:14

Такая же проблема. Случается в неопределенном порядке, через раз, будто выставлено какое-то ограничение, иногда отрабатывает, иногда нет.
Кто сталкивался с такой проблемой?

Код
1. Warning: fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known 

2. php_network_getaddresses: getaddrinfo failed: Name or service not known

Блог о веб-разработке | Каталог сайтов

“SMTP ERROR: Failed to connect to server: php_network_getaddresses: getaddrinfo failed”. Well, this is how my week started. One of my client’s website running WordPress and Easy WP SMTP plugin failed to send mails. Though I rechecked all the mail configurations, test mails via Easy WP SMTP failed with the above error followed by “Name or service not known (0)SMTP connect() failed”. I could solve the issue after an hour of debugging.

Error : Failed to connect to server: php_network_getaddresses: getaddrinfo failed

This error can occur due to two reasons. One, there might me an issue with your DNS settings and second, PHP may not be able to get the network addresses for a given host/domain name.

To start with, I checked the mail settings in Easy WP SMTP plugin and everything was fine. Next, I contacted my DNS provider and confirmed that the issue is not with DNS. So it means, the issue boils down to PHP and as I rightly guessed, PHP was not able to resolve domain names. For example, while debugging, I thought the issue might be due to an outdated Easy WP SMTP plugin, so I decided to update the plugin to only see the error “wordpress.org : Name or service not known”.

It means, for some reason PHP was not able to get the network addresses of the given domain name. To confirm that the issue is with PHP, I wrote a small script as shown below:

<?php
$ip = gethostbyname('www.google.com');
echo $ip;
?>

The function gethostbyname will get the IPv4 address corresponding to the given host name or prints back the host name on failure. In my case, the output was an unmodified host name. It means, gethostbyname has failed to get the IP address of the given host name and that was the culprit.

All I did to fix the issue was to restart the php-fpm daemon and everything worked fine. Unfortunately, I couldn’t find what caused php-fpm to fail, but more often restarting the daemon fixes many issue. Hope it helps someone in need.

  • Ошибка package e1071 is required
  • Ошибка php artisan migrate
  • Ошибка pab чери фора
  • Ошибка photoshop невозможно выполнить запрос перед маркером jpeg
  • Ошибка pab на zanotti