2016-11-12 97 views
1

我有一個使用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; 

連接與設備成功建立,但正確的數據爲n不會發送到設備,否則我會收到設備的響應。

在此先感謝。

回答

1

使用HEX2BIN函數來發送數據試試:

$message = hex2bin('000102010012036bd66f0101000002582617f2586947ae00'); 
+0

是謝謝你,它的工作 – Saad

相關問題