Search code examples
phppythonsocketstcp

Sending Hex values over tcp socket


I have the following python code for sending hexadecimal data to a network device using a TCP socket and it works fine

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()

However I need to convert this code to PHP and I don't know whether this is the correct way to represent the hex data in PHP I tried to run the following code

<?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;

Connection is established successfully with the device but the correct data is not sent to the device otherwise I would have received a response from the device.

Thanks in advance.


Solution

  • Try it using the hex2bin function to send the data:

    $message = hex2bin('000102010012036bd66f0101000002582617f2586947ae00');