用PHP发送TCP数据包

时间:2015-02-10 06:39:52

标签: php sockets tcp websocket

我尝试用PHP发送TCP打包数据到某个ip,我使用下面的代码发送它:

$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    //$bind=socket_bind($socket,'tcp://94.232.171.102');

socket_connect($socket, 'xx.xx.xx.xx', 9001);
$buff='P\00\00\00\e5G\1f\b9\c6\acB\84\15\e7\b3*\17\ab\00G2\n\9c\ba{\a9}\dab"\c31\ed\f7\94\fc\aeX\ab\13\r/\02\ce\83f\bc?\96q\10M\b0\f4\a0\b1\95X\d0\85\10\df$|\de$\b4\f6m\a9\ff%Z\b4\d8\aa\da\bb';
$length = strlen($buff);
$sent = socket_write($socket, $buff, $length);

但是,它不起作用并且没有发送,当我使用像Packet Sender这样的设置它正确发送数据包时,为什么我不能从本地主机上的php发送它

1 个答案:

答案 0 :(得分:3)

至少有一些错误处理,你有更好的机会找到错误。

ini_set('display_errors', true); error_reporting(E_ALL); // <- for debugging purposes only

$socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ( !$socket ) {
    $errno = socket_last_error();
    $error = sprintf('%s (%d)', socket_strerror($errno), $errno);
    trigger_error($error, E_USER_ERROR);
}

if ( !socket_connect($socket, 'xx.xx.xx.xx', 9001) ) {
    $errno = socket_last_error($socket);
    $error = sprintf('%s (%d)', socket_strerror($errno), $errno);
    trigger_error($error, E_USER_ERROR);
}

$buff='P\00\00\00\e5G\1f\b9\c6\acB\84\15\e7\b3*\17\ab\00G2\n\9c\ba{\a9}\dab"\c31\ed\f7\94\fc\aeX\ab\13\r/\02\ce\83f\bc?\96q\10M\b0\f4\a0\b1\95X\d0\85\10\df$|\de$\b4\f6m\a9\ff%Z\b4\d8\aa\da\bb';
$length = strlen($buff);
$sent = socket_write($socket, $buff, $length);
if ( FALSE===$sent ) {
    $errno = socket_last_error($socket);
    $error = sprintf('%s (%d)', socket_strerror($errno), $errno);
    trigger_error($error, E_USER_ERROR);
}
else if ( $length!==$sent ) {
    $msg = sprintf('only %d of %d bytes sent', $length, $sent);
    trigger_error($msg, E_USER_NOTICE);
}