This article mainly introduces the ping port function implemented by php, and analyzes in detail the socket programming skills of PHP in the form of instances, you can refer to the following example to describe the ping port function implemented by php. Share it with you for your reference.
The specific implementation code is as follows:
The code is as follows:
<? Php
/*
* @ Author xujiajay
* @ Date 2010-10-7
* @ Function: the php function that can ping the port.
*
*/
Error_reporting (E_ERROR );
Header ("content-Type: text/html; charset = utf-8 ");
Set_time_limit (120 );
$ Host = isset ($ _ POST ['URL'])? Chop (str_replace ('http: // ', '', $ _ POST ['URL']): 'www .baidu.com ';
$ Port = isset ($ _ POST ['duankou'])? Chop ($ _ POST ['duankou']): '80 ';
$ Num = 10;
Function microtime_float ()
{
List ($ usec, $ sec) = explode ("", microtime ());
Return (float) $ usec + (float) $ sec );
}
Function getsoft ($ host, $ port)
{
$ Fp = @ fsockopen ($ host, $ port, & $ errno, & $ errstr, 3 );
If (! $ Fp) return 'unknown ';
$ Get = "GET/HTTP/1.1 \ r \ nHost:". $ host. "\ r \ nConnection: Close \ r \ n ";
@ Fputs ($ fp, $ get );
$ Data = '';
While ($ fp &&! Feof ($ fp ))
$ Data. = fread ($ fp, 1024 );
@ Fclose ($ fp );
$ Array = explode ("\ n", $ data );
$ K = 2;
For ($ I = 0; $ I <20; $ I ++)
{
If (stristr ($ array [$ I], 'server') {$ k = $ I; break ;}
}
If (! Stristr ($ array [$ k], 'server') return 'unknown ';
Else return str_replace ('server', 'server soft', $ array [$ k]);
}
Function ping ($ host, $ port)
{
$ Time_start = microtime_float ();
$ Ip = gethostbyname ($ host );
$ Fp = @ fsockopen ($ host, $ port, & $ errno, & $ errstr, 1 );
If (! $ Fp) return 'request timed out. '. "\ r \ n ";
$ Get = "GET/HTTP/1.1 \ r \ nHost:". $ host. "\ r \ nConnection: Close \ r \ n ";
@ Fputs ($ fp, $ get );
@ Fclose ($ fp );
$ Time_end = microtime_float ();
$ Time = $ time_end-$ time_start;
$ Time = ceil ($ time * 1000 );
Return 'reply from '. $ ip.': time = '. $ time. 'Ms ';
}
If (isset ($ _ POST ['URL']) & isset ($ _ POST ['duankou'])
{
Echo ''. getsoft ($ host, $ port ).'';
Echo 'pinging '. $ host. '['. gethostbyname ($ host ). '] with Port :'. $ port. 'Of data :'. "\ r \ n ";
Ob_flush ();
Flush ();
For ($ I = 0; $ I <$ num; $ I ++)
{
Echo ping ($ host, $ port );
Ob_flush ();
Flush ();
Sleep (1 );
}
}
?>
I hope this article will help you with PHP programming.