Any off the shelf app to rebroadcast tcp packets? - sockets

I am working with a 3rd party device which opens a tcp port that only allows one connection at a time. If my app connects to the port, all other connections are denied.
I'd like to find an app that basically connects to this port, then allows others to connect to it on a different port.
Any data sent out of the device's port is then rebroadcast to any connected client.
I know how to write such an app, but it seems like it would be something someone else has already thought off and written it & shared, and I could avoid taking the time to write it.
basicaly code would be:
1) start a tcp socket server, binding to TO_PORT (clients connect to this)
2) connect as a client to DEVICE_IP:DEVICE_PORT
3) when data is read into a buffer from DEVICE_IP:DEVICE_PORT, the buffer content is resent to each connected client.
4) everything else that makes it a stable, working program.
This is for windows, and I'd prefer it not require a java install.
My google skills have failed me.
Anyone know of such an app?

Not a complete solution for you, but might be interesting, though
http://www.codeproject.com/KB/IP/serversocket.aspx
http://www.codeproject.com/KB/IP/UniversalTCPSocketClass.aspx

Guess I'll answer my own question.
I implemented the solution my self.
Key points to my solution:
A class named IPClient which wraps up a TcpClient instance, uses async model of calling TcpClient.BeginConnect, BeginRead, etc. It has a Timer used for reconnecting if it loses connection.
This is the class that connects to the device.
It's public interface would look something like this:
public class IPClient{
public event EventHandler<MyConnectedArgs> Connected;
public event EventHandler<MyDisconnectedArgs>Disconnected;
public event EventHandler<MyDataReceivedArgs> DataReceived;
public bool Connect(string address, int port){...}
public bool Disconnect() {...}
}
To open the port that would allow other clients to connect, I used this library: http://codeproject.com/KB/IP/BasicTcpServer.aspx and modified it a bit.
It's job was to open a port, accept connections, and do the following:
in the Connected handler, start the listening port
in the Disconnected handler, stop the listening port
in the DataReceived handler, broadcast the data to any connected clients.
I'll leave out the rest of the boring details, but say it wasn't "too hard", and eventually I just had to roll my own.
command line usage: myapp.exe remote_addr remote_port listen_port
psuedocode/main idea of my program main:
static int Main(string[] args){
//SetConsoleCtrlHandler(my callback re: ctrl+C,etc)
//get command line params
var ipClient = new IPClient();
var myprovider = MyTcpServiceProvider();
var server = new TcpServer(myProvider, listenPort);
ipClient.Connected += (sender, e) => server.Start();
ipClient.Disconnected += (sender,e) => server.Stop();
ipClient.DataReceived += (sender,e)=> provider.BroadcastToClients(e.Data);
ipClient.Connect(remoteAddress, remotePort);
//wait for Ctrl+C or program exit
//shutdown code,etc
return 0;
}

Related

How to make SSL reads block?

I am trying to make SSL_read() block until data is received from the server. I tried setting the socket to blocking in my "connect" code like so
{
u_long iMode = 1;
i = ioctlsocket(sock, FIONBIO, &iMode);
}
but strangely I get a stack overflow exception every time.
Is there another more correct way to do this?
(Note: the app works just fine if I omit this code).
I've searched SO on this issue but everywhere people seem to have just the opposite problem, namely blocking when they want non-blocking.
Code Synopsis:
Get method: TLS_client_method()
Get CTX: SSL_CTX_new(method)
Create socket 'sock'
set socket to blocking (code above)
Connect sock to host on port 443
Create SSL*: ssl=SSL_new(ctx)
SSL_set_fd(ssl, sock)
Do SSL_reads and writes
I achieved what I wanted by switching from SSL_* calls to BIO_* calls for connect, read, write, etc..
The BIO family includes function 'BIO_set_nbio()' which sets blocking/nonblocking mode. Worked great.
Sample Code Synopsis (e.g., for google.com):
Get method: method = TLS_client_method()
Get CTX: ctx = SSL_CTX_new(method)
Create BIO object: bio = BIO_new_ssl_connect( ctx )
Create socket 'sock'
Connect 'sock' to google.com, port 443
Create SSL*: ssl = SSL_new(ctx)
SSL_set_mode( ssl, SSL_MODE_AUTO_RETRY )
BIO_set_conn_hostname( bio, "google.com:443" )
BIO_do_connect( bio )
BIO_set_nbio( bio, mode ) (with mode=0 for blocking)
Now can do blocking BIO_reads and writes (with BIO_read, BIO_write)

Milo: get IP of client

Is there a way to get a Clients IP in Context of a write?
I want to get the IP of an Client that writes to my Milo-OPCUA-Server, so I can handle these writes differently based on the Clients IP (local Clients should be able to write directly on the Server, whilst other writes should get forwarded to another Server)
Okay, this is not part of any official API right now, so it almost certainly will break in the future, but:
With the OperationContext you get when implementing AttributeManager#write(WriteContext, List<WriteValue>):
context.getSession().ifPresent(session -> {
UaStackServer stackServer = context.getServer().getServer();
if (stackServer instanceof UaTcpStackServer) {
ServerSecureChannel secureChannel = ((UaTcpStackServer) stackServer)
.getSecureChannel(session.getSecureChannelId());
Channel channel = secureChannel.attr(UaTcpStackServer.BoundChannelKey).get();
SocketAddress remoteAddress = channel.remoteAddress();
}
});
I'll have to add some official API to do this, probably something hanging off the Session object.

keep all connected clients' ip in netty

My TCP server uses netty.The situation is: When a client connects to the server,I will save the client's ip in a global variable(such as a Map); When the client is disconnected,I will remove the IP from the map.
I used channelConnected() and channelDisconnected() method in SimpleChannelHandler.But my problem is ,some times the channelDisconnected() method cannot catch the event when I think the client is disconnected(maybe the computer closed,or the client process closed,or some other situations...) Can you give me some suggestions.
Just use DefaultChannelGroup which will automatically remove the Channel from it when it was closed.
Alternative you can register a ChannelFutureListener to the Channels close future to do the removal from your map.
Something like this:
channel.getCloseFuture().addListener(new ChannelFutureListener() {
public void operationCompleted(ChannelFuture f) {
map.remove(f.getChannel());
}
});

Redis Connection via socket on Node.js

Because of shared hosting, my redis server on the target host does not run on a port, but on a very specific socket, which can be connected to via the socket file, only accessible to my user.
However, I have not found how I can specify connection via a socket in the node_redis and connect-redis packages, the ones I want to use.
Anyone know how to do it?
Update: My answer below is not really correct. It turns out that the solution in the issue I mention below actually still works. It's more of a coincidence, IMO, but you can do something like this, and it should work:
var redis = require('redis'),
client = redis.createClient('/tmp/redis.sock');
As you see from the code snippet below, this will get passed to net.createConnection which will connect to the unix socket /tmp/redis.sock.
Old answer:
There is a closed issue about this node_redis/issues/204. It seems, thought, that the underlying node.js net.createConnection API has since changed. It looks as though it would be a quite small fix in node_redis' exports.createClient function:
exports.createClient = function (port_arg, host_arg, options) {
var port = port_arg || default_port,
host = host_arg || default_host,
redis_client, net_client;
net_client = net.createConnection(port, host);
redis_client = new RedisClient(net_client, options);
redis_client.port = port;
redis_client.host = host;
return redis_client;
};
It seems as though net.createConnection will attempt to connect to a unix socket if it's called with one argument, that looks like a path. I suggest you implement a fix and send a pull request, since this seems like something worth supporting.
There is no longer a connect string...
var client = redis.createClient(9000); // Open a port on localhost
var client = redis.createClient('/tmp/redis.sock'); // Open a unix socket
var client = redis.createClient(9000, 'example.com');
This, and options are documented on the README.

Test to see if a socket is open in linux

I have a linux server program that waits for incoming connections from a client and depending on what command you send it performs a different connection. Here is the pseudo-code
setup_socket();
while(1)
{
listen();
newfile_descriptor = accept();
int command
read(newfile_descriptor,&command,sizeof(int));
switch(command)
{
...
}
}
But when I want to send more than one command with the same client it listens forever (since a new connection is not being made). Is there a way to check if there is already connection before listening to a new one?
How about a loop where you read the commands:
setup_socket();
while(1)
{
listen();
newfile_descriptor = accept();
int command
command = read(newfile_descriptor,&command,sizeof(int));
while(command) {
switch(command)
{
...
}
// get next command, or figure out closed connection
command = read(newfile_descriptor,&command,sizeof(int));
}
}
You either demultiplex the socket IO with select/poll, or have a separate thread read the commands on the client socket.
How about checking if you can read from the socket some more? I would think you should close your connection at the end of the command if there isn't anything more coming in.
What you need is some basic protocol which allows the client to inform you that it is done sending commands. It could be as simple as the client continues to send commands, then closes the socket when it no longer needs to send any more. In that case, you would simply continue to read from the socket until it is closed. In your pseudo code, it would look something like this:
setup_socket();
while(1) {
listen();
newfile_descriptor = accept();
int command;
do {
command = read(newfile_descriptor,&command,sizeof(int));
if (command > 0) {
switch(command) {
...
}
}
} while (command > 0);
}
To elaborate on Nikolai's response, check out the indispensable Beej's guides.
It is a very standard practice to spawn a new thread immediately after calling accept() inside of your while(1) loop; this thread handles all the communication with the client so that the main thread can continue listen()ing for new incoming connections and accept()ing when they arrive.
Here is the specific section on select(), which I know about, but haven't actually used before.
The very first thing...
Is to move your listen() outside the while loop.
:p