HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

socket_bind

Description

The socket_bind of Sockets for PHP binds a name to a socket.

Syntax

socket_bind(
    Socket $socket,
    string $address,
    int $port = 0
): bool

Parameters

socket

A Socket instance created with socket_create().

address

If the socket is of the AF_INET family, the address is an IP in dotted-quad notation (e.g. 127.0.0.1).

If the socket is of the AF_UNIX family, the address is the path of a Unix-domain socket (e.g. /tmp/mysocket).

port

The port parameter is only used when binding an AF_INET socket, and designates the port on which to listen for connections.

Return

Returns true on success or false on failure.

The error code can be retrieved with socket_last_error(). This code may be passed to socket_strerror() to get a textual explanation of the error.

Examples

1 · socket address · AF_INET

<?

$domain = AF_INET;
$type = SOCK_STREAM;
$protocol = SOL_TCP;

$socket = socket_create($domain, $type, $protocol);

    if($socket === false)
    {
        $error_code = socket_last_error();

        $socket_strerror = socket_strerror($error_code);

        die("socket_create: $socket_strerror");
    }

    $address = '127.0.0.1';

    $return = socket_bind($socket, $address);

    if($return === false)
    {
        $error_code = socket_last_error($socket);

        $socket_strerror = socket_strerror($error_code);

        die("socket_bind: $socket_strerror");
    }

    var_export($return);

socket_close($socket);
true

2 · socket address · AF_UNIX

<?

$domain = AF_UNIX;
$type = SOCK_STREAM;
$protocol = 0;

$socket = socket_create($domain, $type, $protocol);

    if($socket === false)
    {
        $error_code = socket_last_error();

        $socket_strerror = socket_strerror($error_code);

        die("socket_create: $socket_strerror");
    }

    $address = '/tmp/mysocket';

    if(file_exists($address))
    {
        unlink($address);
    }

    $return = socket_bind($socket, $address);

    if($return === false)
    {
        $error_code = socket_last_error($socket);

        $socket_strerror = socket_strerror($error_code);

        die("socket_bind: $socket_strerror");
    }

    var_export($return);

socket_close($socket);
true

3 · port

<?

$domain = AF_INET;
$type = SOCK_STREAM;
$protocol = SOL_TCP;

$socket = socket_create($domain, $type, $protocol);

    if($socket === false)
    {
        $error_code = socket_last_error();

        $socket_strerror = socket_strerror($error_code);

        die("socket_create: $socket_strerror");
    }

    $address = '127.0.0.1';
    $port = 5000;

    $return = socket_bind($socket, $address, $port);

    if($return === false)
    {
        $error_code = socket_last_error($socket);

        $socket_strerror = socket_strerror($error_code);

        die("socket_bind: $socket_strerror");
    }

    var_export($return);

socket_close($socket);
true