gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:42:16 27 4
gpt4 key购买 nike

我有以下 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com