代码语言:javascript复制
<?php
$start = microtime(true);
$result = udpGet('kunkkawu.com', '[::1]', '5353');
$spend = microtime(true) - $start;
echo $result . "n" ;
echo "total time:t".substr($spend * 1000,0,5),"n";
function udpGet($domain = '', $ip = '127.0.0.1', $port = '9595'){
$handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr);
//组装Dns协议头部
$header = parseQuery($domain);
$headerSize = strlen($header);
fwrite($handle, $header, $headerSize);
$result = fread($handle, 10240);
fclose($handle);
return $result;
}
function parseQuery($domain){
if (preg_match("/[a-z|A-Z]/", $domain)==0) { // IP Address
$labelTmp = explode(".", $domain); // reverse ARPA format
for ($i=count($labelTmp)-1; $i>=0; $i--)
{
$labels[] = $labelTmp[$i];
}
$labels[] = "IN-ADDR";
$labels[] = "ARPA";
} else {
$labels = explode(".", $domain);
}
$questionBinary="";
for ($a=0; $a<count($labels); $a )
{
$size = strlen($labels[$a]);
$questionBinary .= pack("C", $size); // size byte first
$questionBinary .= $labels[$a]; // then the label
}
$questionBinary .= pack("C",0); // end it off
$id=rand(1,255)|(rand(0,255)<<8); // generate the ID
$flags=(0x0100 & 0x0300) | 0x0020; // recursion & queryspecmask | authenticated data
$opcode=0x0000; // opcode
// Build the header
$header = '';
$header .= pack('n',$id);
$header .= pack('n',$opcode | $flags);
$header .= pack('n4',1,0,0,0);
$header .= $questionBinary;
$header .= pack('n', 1);
$header .= pack('n',0x0001); // internet class
return $header;
}