Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket connection between C (nanomsg) and Python (non-nanomsg)

I created a socket server in C (using nanomsg) which shall communicate with a Python script (using standard 'Socket' implementation) via TCP:

C-Code (without error handling):

#include <nanomsg/nn.h>
#include <nanomsg/pair.h>
...
char buf[23];
...
socket = nn_socket(AF_SP, NN_PAIR);
nn_bind(socket, "tcp://127.0.0.1:xxxxx");
...
nn_recv(socket, buf, sizeof(buf), 0); 
...
nn_shutdown(socket, endpoint_id);

Python-Code:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect(("127.0.0.1", xxxxx))
s.send('Hello C this is Python')
s.close()

There is no error in Python when connecting to the socket (if the C app is running). However, the C script is idling in method nn_recv and doesn't get any data at all. What am I doing wrong?

First I start the C code in a shell (it idles in method nn_recv). Then I start Python in another shell and expect the C application to receive the data. Both scripts execute without error.

like image 935
linksfate Avatar asked Feb 20 '26 07:02

linksfate


1 Answers

The issue is that nanomsg socket type is not a plain, standard, TCP type. The protocols do not match. You cannot send TCP message to a nanomsg socket and expect that nn_recv will work since the message will not conform to the defined nanomsg SP protocol requirements.

See nanomsg SP protocol header:

0                1               2                3
0 1 2 3 4 5 6 7  8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3  4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|      0x00     |      0x53     |      0x50     |    version    |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|             type              |           reserved            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

First four bytes of the protocol header are used to make sure that the peer's protocol is compatible with the protocol used by the local endpoint.

If the protocol header received from the peer differs, the TCP connection MUST be closed immediately.

That means that any raw TCP send to the nanomsg socket will kill the connection since it does not confirm to the SP protocol.

For more info consult the sp-tcp-mapping-01.txt document here

like image 95
sg7 Avatar answered Feb 21 '26 20:02

sg7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!