Monday, 24 April 2017

Node.js - Sending string containing hex values through TCP socket

I am currently trying to do the following:

Convert data received from a TCP listener into a string containing its equivalent hexadecimal value (e.g. "61 63 68 61 32 30 2d").

Convert the hexadecimal values back to the original data and send it somewhere else.

I managed to convert the data to hex values, however I can't convert it back to the original state.

The goal of doing this is so that I can tunnel internet traffic through a chat application.

I'm trying to make a two Node.js programs: one that opens a listener on localhost, converts all of the data it receives here (to hex) to be sent through a chat application, and the other to receive the data and convert it back to its orignal state.

var net = require('net')

function datatohex(data) {
    var result = data.toString('hex').replace(/(.{2})/g, "$1 ");
    console.log('Data: ' + result);
    return result;
}

function hextodata(data) {
    var result = '';
    var array = data.toString().split(' ');
    console.log('hextodata arg: ' + data);
    for (var i = 0; i < data.length; i++) {
            result += String.fromCharCode(array[i]);
            console.log(String.fromCharCode(array[i]));
    }
    console.log('hextodata result: ' + result);
    return result;
}

var client1 = new net.Socket();
var client2 = new net.Socket();

var server1 = net.createServer(function(socket) {
    socket.on('data', function(data) {
            client1.write(datatohex(data));
    });
    client2.on('data', function(data) {
            socket.write(data);
    });
});

var server2 = net.createServer(function(socket) {
    socket.on('data', function(data) {
            client2.write(hextodata(data));
    });
});

server1.listen(2222, '127.0.0.1');
server2.listen(22222,'127.0.0.1');
client2.connect(22, '127.0.0.1', function() {});
client1.connect(22222, '127.0.0.1', function() {});



via Simon L.

No comments:

Post a Comment