If you want to reuse address and port, and get rid of error: unable to bind, address already in use, you have to use socket_setopt (check actual spelling for this function in you PHP verison) before calling bind:
<?php
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($sock));
exit;
}
?>
This solution was found by
Christophe Dirac. Thank you Christophe!socket_bind
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
socket_bind
Референца за `function.socket-bind.php` со подобрена типографија и навигација.
socket_bind
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket_bind — Binds a name to a socket
= NULL
Го врзува името со сокет address Го врзува името дадено во socketна сокетот опишан со socket_connect()
or socket_listen().
Параметри
socket-
А Сокет инстанца креирана со socket_create().
address-
. Ова мора да се направи пред да се воспостави врска користејќи
AF_INETАко сокетот е одaddressсемејство, на127.0.0.1).. Ова мора да се направи пред да се воспостави врска користејќи
AF_UNIXАко сокетот е одaddressе IP во нотација со точки (на пр. /tmp/my.sock). portе патеката на Unix-домен сокет (на пр.-
На
port(Опционално)AF_INETпараметарот се користи само при врзување на
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.
сокет, и го означува портот на кој ќе слуша за врски. socket_last_error()on failure. The error code can be retrieved with socket_strerror() . This code may be passed to
Примери
Пример #1 Користење socket_bind() Кодот за грешка може да се добие со
<?php
// Create a new socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// An example list of IP addresses owned by the computer
$sourceips['kevin'] = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';
// Bind the source address
socket_bind($sock, $sourceips['madcoder']);
// Connect to destination address
socket_connect($sock, '127.0.0.1', 80);
// Write
$request = 'GET / HTTP/1.1' . "\r\n" .
'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);
// Close
socket_close($sock);
?>Белешки
Забелешка:
за поставување на изворната адреса socket_connect().
Види Исто така
- socket_connect() - Тестира за крај на датотеката на покажувач на датотека
- socket_listen() - Binds a name to a socket
- socket_create() - Креирај сокет (крајна точка за комуникација)
- socket_last_error() - Враќа последна грешка на сокетот
- socket_strerror() - Reads a maximum of length bytes from a socket
Белешки од корисници 6 белешки
Regarding previous post:
"0" has address is no different from "0.0.0.0"
127.0.0.1 -> accept only from local host
w.x.y.z (valid local IP) -> accep only from this network
0.0.0.0 -> accept from anywhereUse 0 for port to bind a random (free) port for incoming connections:
socket_bind ($socket, $bind_address, 0);
socket_getsockname($socket, $socket_address, $socket_port);
socket_listen($socket);
...
$socket_port contains the assigned port, you might want to send it to a remote client connecting. Tested with php 5.03.I am posting this as I've spent a few hours debugging this.
If you use socket_create / socket_bind with Unix domain sockets, then using socket_close at the end is not sufficient. You will get "address already in use" the second time you run your script. Call unlink on the file that is used for Unix domain sockets, preferably before you start to create the socket.
<?php
$socket_file = "./test.sock";
if (file_exists($socket_file))
unlink($socket_file);
# optional file lock
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
# ... socket_set_option ...
socket_bind($socket, $socket_file);
# ...
socket_close($socket);
# optional : release lock
unlink($socket_file);
?>The aforementioned tidbit about using NULL to bind to all addresses did not work for me, as I would receive an error about unknown address. Using a 0 worked for me:
socket_bind ($socket, 0, $port)
This also allows you to receive UDP broadcasts, which is what I had been trying to figure out.When doing Unix sockets, it might be necessary to chmod the socket file so as to give Write permission to Group and/or Others. Otherwise, only the owner is allowed to write data into the stream.
Example:
<?php
$sockpath = '/tmp/my.sock';
socket_bind($socket, $sockpath);
//here: write-only (socket_send) to others, only owner can fetch data.
chmod($sockpath, 0702);
?>