Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: ソケット - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

socket_accept" width="11" height="7"/> <use_soap_error_handler
Last updated: Sun, 25 Nov 2007

view this page in

ソケット関数

導入

ソケット拡張モジュールは、一般的な BSD ソケットに基づくソケット通信に関する低レベルインターフェースを実装し、 クライアントだけでなく、 ソケットサーバとして動作させることが可能となります。

より一般的なクライアントサイドのソケットインターフェースについては、 stream_socket_client()stream_socket_server()fsockopen() および pfsockopen() を参照ください。

ここで説明するソケット関数を使用する場合、多くの関数は C 言語に同じ名前の関数が存在しますが、 しばしば定義が異なっていることに注意してください。 混乱を避けるには、説明をよく読んでください。

このようにソケットプログラミングと異なっている点はありますが、 それでも有用な多くの Unix man ページを参照することができます。 Web 上に C 言語のソケットプログラミングのチュートリアル情報が存在し、 その多くは、若干の修正により、 PHP におけるソケットプログラミングに適用することが可能です。 » Unix Socket FAQ が、 手始めとして適しているでしょう。

注意: この拡張モジュールは » PECL レポジトリに移動 されており、以下のバージョン以降 PHP にバンドルされなくなっています。 PHP 5.3.0.

要件

外部ライブラリを必要としません。

インストール手順

ここに既述されたソケット関数は PHP 拡張モジュールの一部であり、 コンパイル時に configure にオプション --enable-sockets を指定することにより 使用可能となります。

注意: IPv6 サポートは PHP 5.0.0 で追加されました。

実行時設定

設定ディレクティブは定義されていません。

リソース型

socket_accept()socket_create_listen() および socket_create() はソケットリソースを返します。

定義済み定数

以下の定数が定義されています。 この関数の拡張モジュールが PHP 組み込みでコンパイルされているか、 実行時に動的にロードされている場合のみ使用可能です。

AF_UNIX (integer)
AF_INET (integer)
AF_INET6 (integer)
SOCK_STREAM (integer)
SOCK_DGRAM (integer)
SOCK_RAW (integer)
SOCK_SEQPACKET (integer)
SOCK_RDM (integer)
MSG_OOB (integer)
MSG_WAITALL (integer)
MSG_PEEK (integer)
MSG_DONTROUTE (integer)
MSG_EOR (integer)
MSG_EOF (integer)
SO_DEBUG (integer)
SO_REUSEADDR (integer)
SO_KEEPALIVE (integer)
SO_DONTROUTE (integer)
SO_LINGER (integer)
SO_BROADCAST (integer)
SO_OOBINLINE (integer)
SO_SNDBUF (integer)
SO_RCVBUF (integer)
SO_SNDLOWAT (integer)
SO_RCVLOWAT (integer)
SO_SNDTIMEO (integer)
SO_RCVTIMEO (integer)
SO_TYPE (integer)
SO_ERROR (integer)
SOL_SOCKET (integer)
PHP_NORMAL_READ (integer)
PHP_BINARY_READ (integer)
SOL_TCP (integer)
SOL_UDP (integer)

ソケットのエラー

ソケット拡張モジュールは、 強力な BSD ソケットへの有用なインターフェースを提供するために作成されました。 関数は、Win32 および Unix の実装において等しく動作するように注意が払われています。 ソケット関数の多くは特定の条件で失敗し、エラーを記述する E_WARNING メッセージを出力します。 これは、時々開発者が望まない時に発生することがあります。例えば、 関数 socket_read() は突然 E_WARNING メッセージを出力する可能性があります。 これは、予測しない接続断が発生したためです。 @ 演算子により警告出力を抑制し、 socket_last_error() 関数によりアプリケーション内でエラーコードを取得することが一般に行われています。 エラーを記述する文字列を取得するためにこのエラーコードを指定して socket_strerror() 関数をコールすることが可能です。 詳細は、この関数の説明を参照してください。

注意: E_WARNING メッセージは、 ソケット拡張モジュールにより英語で生成されますが、取得されるエラーメッセージは、 現在のロケール (LC_MESSAGES) に依存します。

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

Example#1 ソケットの例: 簡易 TCP/IP サーバ

この例は、簡単な応答サーバです。変数 addressport を設定と実行環境に合うように変更してください。 このサーバに次のようなコマンドで接続することが可能です。 : telnet 192.168.1.53 10000 (ただし、 アドレスとポートは設定に合わせます)入力したものは、サーバ側の出力となり、 エコーバックされます。接続を閉じるには、'quit' を入力します。

#!/usr/local/bin/php -q
<?php
error_reporting
(E_ALL);

/* Allow the script to hang around waiting for connections. */
set_time_limit(0);

/* Turn on implicit output flushing so we see what we're getting
 * as it comes in. */
ob_implicit_flush();

$address '192.168.1.53';
$port 10000;

if ((
$sock socket_create(AF_INETSOCK_STREAMSOL_TCP)) === false) {
    echo 
"socket_create() failed: reason: " socket_strerror(socket_last_error()) . "\n";
}

if (
socket_bind($sock$address$port) === false) {
    echo 
"socket_bind() failed: reason: " socket_strerror(socket_last_error($sock)) . "\n";
}

if (
socket_listen($sock5) === false) {
    echo 
"socket_listen() failed: reason: " socket_strerror(socket_last_error($sock)) . "\n";
}

do {
    if ((
$msgsock socket_accept($sock)) === false) {
        echo 
"socket_accept() failed: reason: " socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    
/* Send instructions. */
    
$msg "\nWelcome to the PHP Test Server. \n" .
        
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
    
socket_write($msgsock$msgstrlen($msg));

    do {
        if (
false === ($buf socket_read($msgsock2048PHP_NORMAL_READ))) {
            echo 
"socket_read() failed: reason: " socket_strerror(socket_last_error($msgsock)) . "\n";
            break 
2;
        }
        if (!
$buf trim($buf)) {
            continue;
        }
        if (
$buf == 'quit') {
            break;
        }
        if (
$buf == 'shutdown') {
            
socket_close($msgsock);
            break 
2;
        }
        
$talkback "PHP: You said '$buf'.\n";
        
socket_write($msgsock$talkbackstrlen($talkback));
        echo 
"$buf\n";
    } while (
true);
    
socket_close($msgsock);
} while (
true);

socket_close($sock);
?>

Example#2 ソケットの例: 簡易 TCP/IP クライアント

この例は、簡単な一回限りの HTTP クライアントです。ここでは、 あるページに接続して HEAD リクエストを送信し、応答を出力た後で終了します。

<?php
error_reporting
(E_ALL);

echo 
"<h2>TCP/IP Connection</h2>\n";

/* Get the port for the WWW service. */
$service_port getservbyname('www''tcp');

/* Get the IP address for the target host. */
$address gethostbyname('www.example.com');

/* Create a TCP/IP socket. */
$socket socket_create(AF_INETSOCK_STREAMSOL_TCP);
if (
$socket === false) {
    echo 
"socket_create() failed: reason: " socket_strerror(socket_last_error()) . "\n";
} else {
    echo 
"OK.\n";
}

echo 
"Attempting to connect to '$address' on port '$service_port'...";
$result socket_connect($socket$address$service_port);
if (
$result === false) {
    echo 
"socket_connect() failed.\nReason: ($result) " socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo 
"OK.\n";
}

$in "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out '';

echo 
"Sending HTTP HEAD request...";
socket_write($socket$instrlen($in));
echo 
"OK.\n";

echo 
"Reading response:\n\n";
while (
$out socket_read($socket2048)) {
    echo 
$out;
}

echo 
"Closing socket...";
socket_close($socket);
echo 
"OK.\n\n";
?>

目次

  • socket_accept — ソケットへの接続を許可する
  • socket_bind — ソケットに名前をバインドする
  • socket_clear_error — ソケットのエラーまたは直近のエラーコードをクリアする
  • socket_close — ソケットリソースを閉じる
  • socket_connect — ソケット上の接続を初期化する
  • socket_create_listen — 接続を受けつけるためにポートにソケットをオープンする
  • socket_create_pair — 区別できないソケットの組を作成し、配列に保存する
  • socket_create — ソケット(通信時の終端)を作成する
  • socket_get_option — ソケットのオプションを取得する
  • socket_getpeername — 指定したソケットのリモート側に問い合わせ、その型に応じてホスト/ポート、あるいは Unix ファイルシステムのパスを返す
  • socket_getsockname — 指定したソケットのローカル側に問い合わせ、その型に応じてホスト/ポート、あるいは Unix ファイルシステムのパスを返す
  • socket_last_error — ソケットの直近のエラーを返す
  • socket_listen — ソケット上で接続待ち(listen)する
  • socket_read — ソケットから最大バイト長まで読みこむ
  • socket_recv — 接続したソケットからデータを受信する
  • socket_recvfrom — 接続しているかどうかによらず、ソケットからデータを受信する
  • socket_select — 与えられたソケットの配列に対し、指定した有効時間で select() システムコールを実行する
  • socket_send — 接続したソケットにデータを送信する
  • socket_sendto — 接続しているかどうかによらずソケットにメッセージを送信する
  • socket_set_block — ソケットリソースをブロックモードに設定する
  • socket_set_nonblock — ソケットリソースを非ブロックモードに設定する
  • socket_set_option — ソケットのオプションを設定する
  • socket_shutdown — 受信、送信、または送受信用のソケットをシャットダウンする
  • socket_strerror — ソケットエラーの内容を文字列として返す
  • socket_write — ソケットに書き込む


add a note add a note User Contributed Notes
ソケット
david dot schueler at tel-billig dot de
16-Jan-2008 08:37
Another Workaround for sending UDP Broadcasts to 255.255.255.255 and receiving the responses on a specific port:
<?php
// NOTE!
// This is quick and dirty code! It comes without error handling!

// Timeout in seconds waiting for a response.
$timeout = 10;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($sock,"0.0.0.0",10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World";
socket_sendto($sock, $buf, strlen($buf), 0, "255.255.255.255", 10000);
socket_set_block($sock);
socket_set_option($sock,
                        
SOL_SOCKET,
                        
SO_RCVTIMEO,
                         array(
"sec"=>10,"usec"=>0));
$timeout += time();
while (
time() <= $timeout-1) {
 if ((
$len = @socket_recvfrom($sock,$ret,2048,0,$cIP,$cPort)) != false) {
  echo
bin2hex($ret);
 }
}
socket_set_nonblock($sock);
socket_close($sock);
?>
david dot schueler at tel-bilig dot de
14-Jan-2008 08:02
NOTE! If you are trying to send a broadcast-message using this code you _may_ get a "Permission denied"-Error at socket_connect, even if you are running this as root on a linux box.
<?php
$sock
= socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock,"255.255.255.255", 10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World!";
socket_write($sock,$buf,strlen($buf));
socket_close($sock);
?>
The only workaround for this is to get the broadcast address of the interface and walk through all IPs with a for-loop.
nakarman at gmail dot com
11-Nov-2007 06:01
I have beaten the zombies with this code:
pcntl_signal(SIGCHLD, SIG_IGN);
pcntl_signal(SIGTERM, SIG_DFL);
pcntl_signal(SIGINT, SIG_DFL);

server now exits with `kill`
White-Gandalf
03-Sep-2007 04:03
At the moment (2007-09), i don't find this extension in the PECL, but instead in the usual php extension directory. It needs to be included in the php-ini:

extension = php_sockets.dll

(or ".so" - whatever for your system).
roberto at spadim dot com dot br
12-Feb-2007 03:27
Wake on Lan , working ok without configurations, and some features

<?php
function wake_on_lan($mac,$addr=false,$port=7) {
   
//Usage
    //    $addr:
    //    You will send and broadcast tho this addres.
    //    Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //    to do anything with this.
    //    Since 255.255.255.255 have permission denied problems you can use addr=false to get all broadcast address from ifconfig command
    //    addr can be array with broadcast IP values
    //    $mac:
    //    You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //    Mac can be array too   
    //
    //Return
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example 1
    //    When the message has been send you will see the message "Done...."
    //    if ( wake_on_lan('00:00:00:00:00:00'))
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
   
if ($addr===false){
       
exec("ifconfig | grep Bcast | cut -d \":\" -f 3 | cut -d \" \" -f 1",$addr);
       
$addr=array_flip(array_flip($addr));
    }
    if(
is_array($addr)){
       
$last_ret=false;
        for (
$i=0;$i<count($ret);$i++)
            if (
$ret[$i]!==false)
               
$last_ret=wake_on_lan($mac,$ret[$i],$port);
        return(
$last_ret);
    }
    if (
is_array($mac)){
       
$ret=array();
        foreach(
$mac as $k=>v)
           
$ret[$k]=wake_on_lan($v,$addr,$port);
        return(
$ret);
    }
   
//Check if it's an real MAC-addres and split it into an array
   
$mac=strtoupper($mac);
    if (!
preg_match("/([A-F0-9]{1,2}[-:]){5}[A-F0-9]{1,2}/",$mac,$maccheck))
        return
false;
   
$addr_byte = preg_split("/[-:]/",$maccheck[0]);
 
   
//Creating hardware adress
   
$hw_addr = '';
    for (
$a=0; $a < 6; $a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
       
$hw_addr .= chr(hexdec($addr_byte[$a]));
   
   
//Create package data
   
$msg = str_repeat(chr(255),6);
    for (
$a = 1; $a <= 16; $a++)
       
$msg .= $hw_addr;
   
//Sending data
   
if (function_exists('socket_create')){
       
//socket_create exists
       
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);    //Can create the socket
       
if ($sock){
           
$sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set
           
if ($sock_data){
               
$sock_data = socket_sendto($sock, $msg, strlen($msg), 0, $addr,$port); //Send data
               
if ($sock_data){
                   
socket_close($sock); //Close socket
                   
unset($sock);
                    return(
true);
                }
            }
        }
        @
socket_close($sock);
        unset(
$sock);
    }
   
$sock=fsockopen("udp://" . $addr, $port);
    if(
$sock){
       
$ret=fwrite($sock,$msg);
       
fclose($sock);
    }
    if(
$ret)
        return(
true);
    return(
false);   
}
?>
chabotc at xs4all dot nl
18-Dec-2006 06:01
For an implementation of a Socket Daemon framework that can handle both client and server sockets, async (non blocking) communication, which is flexible and easy to use see:

http://www.chabotc.nl/php/php-socket-daemon-library/
karadog at gmail dot com
02-Oct-2006 03:50
A simple HTTP request class using socket.

<?php
class HttpRequest
{
    var
$sHostAdd;
    var
$sUri;
    var
$iPort;
   
    var
$sRequestHeader;
   
    var
$sResponse;
   
    function
HttpRequest($sUrl)
    {
       
$sPatternUrlPart = '/http:\/\/([a-z-\.0-9]+)(:(\d+)){0,1}(.*)/i';
       
$arMatchUrlPart = array();
       
preg_match($sPatternUrlPart, $sUrl, $arMatchUrlPart);
       
       
$this->sHostAdd = gethostbyname($arMatchUrlPart[1]);
        if (empty(
$arMatchUrlPart[4]))
        {
           
$this->sUri = '/';
        }
        else
        {
           
$this->sUri = $arMatchUrlPart[4];
        }
        if (empty(
$arMatchUrlPart[3]))
        {
           
$this->iPort = 80;
        }
        else
        {
           
$this->iPort = $arMatchUrlPart[3];
        }
       
       
$this->addRequestHeader('Host: '.$arMatchUrlPart[1]);
       
$this->addRequestHeader('Connection: Close');
    }
   
    function
addRequestHeader($sHeader)
    {
       
$this->sRequestHeader .= trim($sHeader)."\r\n";
    }
   
    function
sendRequest($sMethod = 'GET', $sPostData = '')
    {
       
$sRequest = $sMethod." ".$this->sUri." HTTP/1.1\r\n";
       
$sRequest .= $this->sRequestHeader;
        if (
$sMethod == 'POST')
        {
           
$sRequest .= "Content-Type: application/x-www-form-urlencoded\r\n";
           
$sRequest .= "Content-Length: ".strlen($sPostData)."\r\n";
           
$sRequest .= "\r\n";
           
$sRequest .= $sPostData."\r\n";
        }
       
$sRequest .= "\r\n";
       
       
$sockHttp = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if (!
$sockHttp)
        {
            die(
'socket_create() failed!');
        }
       
       
$resSockHttp = socket_connect($sockHttp, $this->sHostAdd, $this->iPort);
        if (!
$resSockHttp)
        {
            die(
'socket_connect() failed!');
        }
       
       
socket_write($sockHttp, $sRequest, strlen($sRequest));
       
       
$this->sResponse = '';
        while (
$sRead = socket_read($sockHttp, 4096))
        {
           
$this->sResponse .= $sRead;
        }
       
       
socket_close($sockHttp);
    }
   
    function
getResponse()
    {
        return
$this->sResponse;
    }
   
    function
getResponseBody()
    {
       
$sPatternSeperate = '/\r\n\r\n/';
       
$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);
        return
$arMatchResponsePart[1];
    }
}
?>
aeolianmeson at NOSPAM dot blitzeclipse dot com
30-May-2006 04:13
There is a fantastic book on this library called 'TCP/IP Sockets in C' (ISBN 1558608265), that covers all of the ins and outs, quirks, and everything else that goes on. It's written for C, of course, but it could have easily been written for PHP with almost no serious code differences.

Dustin
f.moisant
18-May-2006 09:41
This function to send Magic Packet works really !!!

/********/
<?php
function wake($ip, $mac, $port)
{
 
$nic = fsockopen("udp://" . $ip, $port);
  if(
$nic)
  {
   
$packet = "";
    for(
$i = 0; $i < 6; $i++)
      
$packet .= chr(0xFF);
    for(
$j = 0; $j < 16; $j++)
    {
      for(
$k = 0; $k < 6; $k++)
      {
       
$str = substr($mac, $k * 2, 2);
       
$dec = hexdec($str);
       
$packet .= chr($dec);
      }
    }
   
$ret = fwrite($nic, $packet);
   
fclose($nic);
    if(
$ret)
      return
true;
  }
  return
false;
}
?>

/********/

Executed with:
wake('123.123.123.123', '112233445566', 9);
goldemish at tiscali dot it
24-Apr-2006 10:52
Function to send Magic Packets for Wake on Wan (WOW) or Wake on Lan(WOL), without sockets library.

<?
function WakeOnLan($ip, $mac, $port)
{
       
$packet = "";
        for(
$i = 0; $i < 6; $i++) $packet .= chr(0xFF);
        for(
$i = 0; $i < 6; $i++) $packet .= chr((int)substr($mac, $i, $i + 2));
       
$nic = fsockopen("udp://" . $ip, $port));
        if(
$nic==false){
            return
false;
           
fclose($nic);
        }
       
fwrite($nic, $packet);
       
fclose($nic);
        return
true;
}
?>
arplynn at gmail dot com
22-Jan-2006 05:19
If you want to use any complicated preexisting protocols, you may find the function pack (http://php.net/pack) useful.
bmatheny at mobocracy dot net
17-Sep-2005 10:31
A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create(AF_INET, SOCK_DGRAM, 0);
$opt_ret = socket_set_option($sock, 1, 6, TRUE);
$send_ret = socket_sendto($sock, $bc_string, strlen($bc_string), 0, '230.0.0.1', 4446);

Checking the return types is needed, but this does allow for you to multicast from php code.
philip at birk-jensen dot dk
22-Aug-2005 10:22
I've been using the ICMP Checksum calculation function written by Khaless [at] bigpond [dot] com. But when having an odd length of data, it failed, so I made my own instead, which adds a 0 if the data length is odd:
<?php
function icmpChecksum($data)
{
   
// Add a 0 to the end of the data, if it's an "odd length"
   
if (strlen($data)%2)
       
$data .= "\x00";
   
   
// Let PHP do all the dirty work
   
$bit = unpack('n*', $data);
   
$sum = array_sum($bit);
   
   
// Stolen from: Khaless [at] bigpond [dot] com
    // The code from the original ping program:
    //    sum = (sum >> 16) + (sum & 0xffff);    /* add hi 16 to low 16 */
    //    sum += (sum >> 16);            /* add carry */
    // which also works fine, but it seems to me that
    // Khaless will work on large data.
   
while ($sum>>16)
       
$sum = ($sum >> 16) + ($sum & 0xffff);
   
    return
pack('n*', ~$sum);
}
?>
m dot hoppe at hyperspeed dot de
03-Sep-2004 10:36
Very good step-by-step tutorial for a network daemon is here:
http://www.php-mag.net/itr/online_artikel [next]
[before] /psecom,id,484,nodeid,114.html

Sorry, I was forced to split this link. :-(
aidan at php dot net
18-Aug-2004 09:08
hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
Toppi at kacke dot de
18-Jun-2004 11:06
Here another socketclass which can handle the most importand things.
http://kacke.de/php_samples/source.php?f=socke.inc

Here a little Chatserver based on this class.
http://kacke.de/php_samples/source.php?f=pline.php

Maybe its helpful :)

Toppi
KnoB
11-Jun-2004 09:35
A little example that shows how to implement a simple multi-client iterative server (without forking). Launch the server and connect multiple telnet clients on it. It's a basic chat program.

#!/usr/bin/php -q
<?php
error_reporting
(E_ALL);

set_time_limit(0);
ob_implicit_flush();

$address = '127.0.0.1';
$port = 8888;

function
handle_client($allclient, $socket, $buf, $bytes) {
    foreach(
$allclient as $client) {
       
socket_write($client, "$socket wrote: $buf");
    }
}

if ((
$master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
    echo
"socket_create() failed: reason: " . socket_strerror($master) . "\n";
}

socket_set_option($master, SOL_SOCKET,SO_REUSEADDR, 1);

if ((
$ret = socket_bind($master, $address, $port)) < 0) {
    echo
"socket_bind() failed: reason: " . socket_strerror($ret) . "\n";
}

if ((
$ret = socket_listen($master, 5)) < 0) {
    echo
"socket_listen() failed: reason: " . socket_strerror($ret) . "\n";
}

$read_sockets = array($master);

while (
true) {
   
$changed_sockets = $read_sockets;
   
$num_changed_sockets = socket_select($changed_sockets, $write = NULL, $except = NULL, NULL);
    foreach(
$changed_sockets as $socket) {
        if (
$socket == $master) {
            if ((
$client = socket_accept($master)) < 0) {
                echo
"socket_accept() failed: reason: " . socket_strerror($msgsock) . "\n";
                continue;
            } else {
               
array_push($read_sockets, $client);
            }
        } else {
           
$bytes = socket_recv($socket, $buffer, 2048, 0);
            if (
$bytes == 0) {
               
$index = array_search($socket, $read_sockets);
                unset(
$read_sockets[$index]);
               
socket_close($socket);
            } else {
               
$allclients = $read_sockets;
               
array_shift($allclients);    // remove master
               
handle_client($allclients, $socket, $buffer, $bytes);
            }
        }
       
    }
}

?>
noSanity
18-May-2004 11:40
I have searched long and hard for a ping script that does NOT use EXEC() or SYSTEM(). So far, I have found nothing, so I decided to write my own, which was a task to say the least.

First off, I would like to thank Khaless for their checksum function, converting it from C looked like a task in itself.

Here is the class I wrote
<?php

class Net_Ping
{
  var
$icmp_socket;
  var
$request;
  var
$request_len;
  var
$reply;
  var
$errstr;
  var
$time;
  var
$timer_start_time;
  function
Net_Ping()
  {
   
$this->icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
   
socket_set_block($this->icmp_socket);
  }
 
  function
ip_checksum($data)
  {
     for(
$i=0;$i<strlen($data);$i += 2)
     {
         if(
$data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
         else
$bits = unpack('C*',$data[$i]);
        
$sum += $bits[1];
     }
    
     while (
$sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
    
$checksum = pack('n1',~$sum);
     return
$checksum;
  }

  function
start_time()
  {
   
$this->timer_start_time = microtime();
  }
 
  function
get_time($acc=2)
  {
   
// format start time
   
$start_time = explode (" ", $this->timer_start_time);
   
$start_time = $start_time[1] + $start_time[0];
   
// get and format end time
   
$end_time = explode (" ", microtime());
   
$end_time = $end_time[1] + $end_time[0];
    return
number_format ($end_time - $start_time, $acc);
  }

  function
Build_Packet()
  {
   
$data = "abcdefghijklmnopqrstuvwabcdefghi"; // the actual test data
   
$type = "\x08"; // 8 echo message; 0 echo reply message
   
$code = "\x00"; // always 0 for this program
   
$chksm = "\x00\x00"; // generate checksum for icmp request
   
$id = "\x00\x00"; // we will have to work with this later
   
$sqn = "\x00\x00"; // we will have to work with this later

    // now we need to change the checksum to the real checksum
   
$chksm = $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);

   
// now lets build the actual icmp packet
   
$this->request = $type.$code.$chksm.$id.$sqn.$data;
   
$this->request_len = strlen($this->request);
  }
 
  function
Ping($dst_addr,$timeout=5,$percision=3)
  {
   
// lets catch dumb people
   
if ((int)$timeout <= 0) $timeout=5;
    if ((int)
$percision <= 0) $percision=3;
   
   
// set the timeout
   
socket_set_option($this->icmp_socket,
     
SOL_SOCKET// socket level
     
SO_RCVTIMEO, // timeout option
     
array(
      
"sec"=>$timeout, // Timeout in seconds
      
"usec"=>// I assume timeout in microseconds
      
)
      );

    if (
$dst_addr)
    {
      if (@
socket_connect($this->icmp_socket, $dst_addr, NULL))
      {
     
      } else {
       
$this->errstr = "Cannot connect to $dst_addr";
        return
FALSE;
      }
     
$this->Build_Packet();
     
$this->start_time();
     
socket_write($this->icmp_socket, $this->request, $this->request_len);
      if (@
socket_recv($this->icmp_socket, &$this->reply, 256, 0))
      {
       
$this->time = $this->get_time($percision);
        return
$this->time;
      } else {
       
$this->errstr = "Timed out";
        return
FALSE;
      }
    } else {
     
$this->errstr = "Destination address not specified";
      return
FALSE;
    }
  }
}

$ping = new Net_Ping;
$ping->ping("www.google.ca");

if (
$ping->time)
  echo
"Time: ".$ping->time;
else
  echo
$ping->errstr;

?>

Hope this saves some troubles.

noSanity
Khaless [at] bigpond [dot] com
19-Jan-2004 02:55
I spent a while trying to use SOCK_RAW to send ICMP request packets so i could ping. This however lead me to need the internet checksum written as a php function, which was a little hard because of the way PHP handles variable types. Anyway, to save others the effort heres what i came up with, this returns Checksum for $data

<?PHP
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
   
// 32-bit accumilator, 16 bits at a time, adds odd bit on at end
   
for($i=0;$i<strlen($data);$i += 2)
    {
        if(
$data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
        else
$bits = unpack('C*',$data[$i]);
       
$sum += $bits[1];
    }
   
   
// Fold 32-bit sum to 16 bits
   
while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
   
$checksum = pack('n1',~$sum);
    return
$checksum;
}
?>

And with this i was able to construct a correct PING Request.
murzik [at] pisem dot net
06-Oct-2003 08:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey (at SPR dot AT), upgraded by Murzik <tomurzik@inbox.ru>

flush();

function
WakeOnLan($addr, $mac)
{
 
$addr_byte = explode(':', $mac);
 
$hw_addr = '';

 for (
$a=0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));

 
$msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);

 for (
$a = 1; $a <= 16; $a++)    $msg .= $hw_addr;

 
// send it to the broadcast address using UDP
 // SQL_BROADCAST option isn't help!!
 
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
 if (
$s == false)
 {
  echo
"Error creating socket!\n";
  echo
"Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
 }
 else
 {
 
// setting a broadcast option to socket:
 
$opt_ret socket_set_option($s, 1, 6, TRUE);
  if(
$opt_ret < 0)
  {
   echo
"setsockopt() failed, error: " . strerror($opt_ret) . "\n";
  }
 
$e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
 
socket_close($s);
  echo
"Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
 }
}

#WakeOnLan('yourIPorDomain.dyndns.org', 'your:MAC:address');
#WakeOnLan('192.168.0.2', '00:30:84:2A:90:42');
#WakeOnLan('192.168.1.2', '00:05:1C:10:04:05');

//if you have switch or other routing devices in LAN, sendign to
// the local IP isn't helps! you need send to the broadcast address like this:
WakeOnLan('192.168.1.255', '00:05:1C:10:04:05');

?>
bart at mediawave dot nl
06-Jan-2003 08:42
Here is a good article on some of the differences between HTTP 1.0 and HTTP 1.1.

http://wireless.java.sun.com/midp/questions/chunking/
talmage at usi-rpg dot com
04-Jan-2003 05:02
I have spent the past two days ripping out hair trying to figure out how to prevent zombie processes w/the examples above and I just happend to find this in the manual for another lanuage, felt it neccassry to port it here.

--begin copy--
van[at]webfreshener[dot]com
11-Oct-2002 02:53
 
Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding <b>--enable-sigchild</b> to your configure will get rid of the problem.

Hope that saves some hair tearing :]

--end copy--

Thanks vam@wenfreshener.com !!!!
saryon at unfix dot org
10-Jul-2002 01:42
I found this EXTREMELY useful link on the zend php
mailing list:

http://www.zend.com/lists/php-dev/200205/msg00286.html

It's about being able to use multiple connections
in a php socket server, WITHOUT having
to use those threads everyone seems to be
so very fond of.
works very well :)
(ps: i didn't make it, so....don't say thanks to me ;),
thank him)
daniel[at]lorch.cc
23-Feb-2002 02:32
"Beej's Guide to Network Programming" is an absolutely excellent and easy to understand tutorial to socket programming. It was written for C developers, but as the socket functions in PHP are (almost) analoguous, this should not be a problem.

http://www.ecst.csuchico.edu/~beej/guide/net/
davem at olsusa dot com
18-Feb-2002 11:27
Below is a simple forked daemon I wrote in PHP. I haven't seen one yet anywhere else, so I thought some people might be wondering how to do  it. Execute
with php -q <file>

<?PHP

/*

    PHP forked daemon
    Standalone PHP binary must be compiled with --enable-sockets and --enable-pcntl
    Dave M. -2002
        Online Services USA
*/

function sig_handler($signo) {

     switch(
$signo) {
         case
SIGTERM:
            
// handle shutdown tasks
            
exit;
             break;
         case
SIGHUP:
            
// handle restart tasks
            
break;
         case
SIGUSR1:
             print
"Caught SIGUSR1...\n";
             break;
         case
SIGCHLD:
             while(
pcntl_waitpid(-1,$status,WNOHANG)>0 ) {
             }
             break;
         case
SIGINT:
        exit;
         default:
            
// not implemented yet...
            
break;
     }

}

function
interact($sock) {

   
// Custom code goes here... e.g: socket_read() socket_write()...

}

function
become_daemon() {

   
$child = pcntl_fork();
    if(
$child) {
        exit;
// kill parent
   
}
   
posix_setsid(); // become session leader
   
chdir("/");
   
umask(0); // clear umask
   
return posix_getpid();

}

function
open_pid_file($file) {

    if(
file_exists($file)) {
       
$fp = fopen($file,"r");
       
$pid = fgets($fp,1024);
       
fclose($fp);
        if(
posix_kill($pid,0)) {
            print
"Server already running with PID: $pid\n";
            exit;
        }
        print
"Removing PID file for defunct server process $pid\n";
        if(!
unlink($file)) {
            print
"Cannot unlink PID file $file\n";
            exit;
        }
    }
    if(
$fp = fopen($file,"w")) {
        return
$fp;
    } else {
        print
"Unable to open PID file $file for writing...\n";
        exit;
    }
}

function
change_identity($uid,$gid) {
    global
$pid_file;
    if(!
posix_setgid($gid)) {
        print
"Unable to setgid to $gid!\n";
       
unlink($pid_file);
        exit;
    }   
    if(!
posix_setuid($uid)) {
        print
"Unable to setuid to $uid!\n";
       
unlink($pid_file);
        exit;
    }
   
   
}

error_reporting (4);

set_time_limit (0);

ob_implicit_flush ();

$pid_file = '/tmp/php_daemon.pid';

$underpriv_uid = '99'; // uid 99 == user nobody, at least on my system.
$underpriv_gid = '99';

$port = 10000;
$address = 0; // 0 binds to all addresses, may not work on fbsd

$quit = 0;

pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGINT, "sig_handler");

$fh = open_pid_file($pid_file);

if ((
$sock = socket_create (AF_INET, SOCK_STREAM, 0)) < 0) {
    print
"socket_create() failed: reason: " . socket_strerror ($sock) . "\n";
}

if ((
$ret = socket_bind ($sock, $address, $port)) < 0) {
    print
"socket_bind() failed: reason: " . socket_strerror ($ret) . "\n";
}

if ((
$ret = socket_listen ($sock, 0)) < 0) {
    print
"socket_listen() failed: reason: " . socket_strerror ($ret) . "\n";
}

change_identity($underpriv_uid,$underpriv_gid);

print
"Server ready. Waiting for connections.....\n";

$pid = become_daemon();
fputs($fh,$pid);
fclose($fh);

while(!
$quit) {

    if ((
$connection = socket_accept($sock)) < 0) {
       
next;
    }
   
    if( (
$child = pcntl_fork()) == -1 ) {
        print 
"Could not fork!!\n";
        print
"Dying...\n";
       
$quit++;
    }
    elseif(
$child == 0) {
       
socket_close($sock);
       
interact($connection);
        exit;
    }
   
   
socket_close($connection);
   
}

if(
posix_getpid() == $pid) {
   
unlink($pid_file);
}
judeman at yahoo dot com
05-Jun-2001 02:49
After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions.  Here's how I did it:

<?php
   
// here is a basic opening of the a socket.  AF_INET specifies the internet domain.  SOCK_DGRAM
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
   
$sock = socket(AF_INET, SOCK_DGRAM, 0);

   
// if the file handle assigned to socket is less than 0 then opening the socket failed
   
if($sock < 0)
    {
        echo
"socket() failed, error: " . strerror($sock) . "\n";
    }

   
// here's where I set the socket options, this is essential to allow broadcasting.  An earlier comment (as of
// June 4th, 2001) explains what the parameters are.  For my purposes (UDP broadcasting) I need to set
// the broadcast option at the socket level to true.  In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3).  These may exist in PHP but I couldn't reference them 
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively).  This
// function is basically just a wrapper to the C  function so check out the C documentation for more info
   
$opt_ret = setsockopt($sock, 1, 6, TRUE);

   
// if the return value is less than one, an error occured setting the options
   
if($opt_ret < 0)
    {
        echo
"setsockopt() failed, error: " . strerror($opt_ret) . "\n";
    }

   
// finally I am ready to broad cast something.  The sendto function allows this without any
// connections (essential for broadcasting).  So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096.  The 0 (param 4) specifies no special
// options, you can read about the options with man sendto
   
$send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured
   
if($send_ret < 0)
    {
    echo
"sendto() failed, error: " . strerror($send_ret) . "<BR>\n";            }
// be sure to close your socket when you're done
close($sock);

 
show source | credits | sitemap | contact | advertising | mirror sites