phpdockerphp-socket

PHP7 issue : socket_sendto occurred "Unknown host"


Q : Please let i know why socket_sendto function occurred Unknown host error

env

centos 7.9
php-fpm 7.4 AND php-fpm 8.1
in docker container

/etc/hosts

<docker net ip>     <docker container id>
127.0.0.1           nd.domain.com

execution

php -q SERVER.php

source

#!/usr/local/bin/php -q
<?php

// error_reporting(E_ALL);
// set_time_limit(0);
// ob_implicit_flush();

$address = '0.0.0.0';
$port = 80;
echo "server now start\r\n";

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or dir("create failed this socket");

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}


socket_bind($socket, $address, $port) or dir("Failed to bind to (".$address.":".$port.")");
echo "server binded\r\n";





$messageBuffer = "";

$clients = [];
while (true){

    if (@socket_recvfrom($socket, $messageBuffer, 2048, MSG_WAITALL, $ip, $port)) {
        $address = "$ip:$port";
        echo "Receive data : " . $messageBuffer . " FROM " . $address. "\r\n";

        if (!isset($clients[$address])) 
            $clients[$address] = array();
     
        $data = "hello-world";
        $client_ip = gethostbyname($address);
        echo "callback - send to " . $client_ip . "\r\n";
        if (@socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)) {
            echo "sendto ok";
        } else {
            echo socket_strerror(socket_last_error($socket))."\r\n";
        };
    } else {
        echo socket_strerror(socket_last_error($socket))."\r\n";
    };

    



        // $clients[$address]->handlePacket($buffer);
}

socket_close($socket);

//socket_close 

// namespace cgiServer;

    // include_once './server_fn.php';
    // include_once './socketManager.php';
    // include_once './socketManagerSessionCtl.php';

    // // 무한정 실행하기 위해 시간한계를 0으로 설정한다.
    // set_time_limit(0);

    // // 대기할 IP 주소와 포트번호를 설정한다
    // $unit = new \cgiServer\server\manageUnit('192.168.35.29', 9000);

    // //서버 실행
    // $unit->serverOpen();
    // exit;
?>

server log

with php-fpm 8.1 (display error on)
server now start
server binded
Receive data : hello world FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345

Warning: socket_sendto(): Host lookup failed [-10000]: Unknown error -10000 in [err-path] on line 47
Unknown error -10000

with php-fpm 7.4 (display error off)
Receive data : 0101010101! FROM 123.123.123.12:12345
callback - send to 123.123.123.12:12345
Unknown host

Solution

  • $client_ip and $address returns 123.123.123.123:12345

    $ip returns 123.123.123.123

    so i replace like that

    @socket_sendto($socket, $data, strlen($data), 0, $client_ip, $port)
    

    to

    @socket_sendto($socket, $data, strlen($data), 0, $ip, $port)