php - 通过 tcp 套接字发送十六进制值

标签 php python sockets tcp

我有以下 python 代码,用于使用 TCP 套接字将十六进制数据发送到网络设备,它工作正常

import socket
import binascii

def Main():
    host = '192.168.2.3'
    port = 8000

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))
    print 'connected'
    message = '\x00\x01\x02\x01\x00\x12\x03\x6b\xd6\x6f\x01\x01\x00\x00\x02\x58\x69\x47\xae\x58\x69\x47\xae\x00'
    s.send(message)
    print 'sent command'

    data = s.recv(1024)
    s.close()
    print type(data)

    print binascii.hexlify(data)

if __name__ == '__main__':
    Main()

但是我需要将此代码转换为 PHP 并且我不知道这是否是在 PHP 中表示十六进制数据的正确方法 我尝试运行以下代码

<?php

if(!($sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname("tcp"))))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Connect socket to remote server
if(!socket_connect($sock , '192.168.2.3' , 8000))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not connect: [$errorcode] $errormsg \n");
}

echo "Connection established \n";
//Is this proper representation of the hexadecimal data
$message = '\x00\x01\x02\x01\x00\x12\x03\x6b\xd6\x6f\x01\x01\x00\x00\x02\x58\x26\x17\xf2\x58\x69\x47\xae\x00';

//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not send data: [$errorcode] $errormsg \n");
}

echo "Message send successfully \n";

//Now receive reply from server
if(socket_recv ( $sock , $buf , 2 , MSG_WAITALL ) === FALSE)
{
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not receive data: [$errorcode] $errormsg \n");
}

//print the received message
echo $buf;

已成功与设备建立连接,但未向设备发送正确的数据,否则我会收到设备的响应。

提前致谢。

最佳答案

尝试使用 hex2bin 函数发送数据:

$message = hex2bin('000102010012036bd66f0101000002582617f2586947ae00');

关于php - 通过 tcp 套接字发送十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40565553/

相关文章:

python - 如何在 DecisionTreeClassifier 中设置类权重以进行多类设置

python - Flask:创建在多个请求中保留的对象

python - Scipy leastsq() 函数开销

php - 使用多个查询快速刷新 php get

linux - 为什么创建的 socketchannels 可以超过 max open files?

java - 将对象流与 SSL 套接字一起使用时出错

javascript - Node.js 服务中的 socket.io 事件使用的套接字

php - 检查字符串是否为 URL 的最简单方法

php - Moodle:从网络服务获取用户图片

php - 在 php/mysql 中跟踪记录更新之间的变化