3

I'm trying to monitor a unix socket ("/tmp/mysocket").

I can do this fine in Node.js: it raises an event when

  1. a socket is bound
  2. someone connects to the socket
  3. data is sent to the socket and
  4. the socket is disconnected.

I'm trying to now do this in C/C++: I want to monitor "/tmp/mysocket" for the above events. I've looked at libevent (which I'd preferably like to use), but see that it requires an IP:port. Is there any way to monitor unix sockets?

Or can anyone suggest another C/C++ solution?

spaceKelan
  • 67
  • 7
Eamorr
  • 9,872
  • 34
  • 125
  • 209

1 Answers1

5

You could monitor a UNIX domain socket just like a regular file, since it can be operated like a file, e.g. in libev,

struct sockaddr_un address;
memset(&address, 0, sizeof(address));
address.sun_family = AF_LOCAL;
strcpy(address.sun_path, "/tmp/mysocket");

bind(socket, (struct sockaddr*)(&address), sizeof(address));
listen(socket, 5);

// now listen if someone has connected to the socket.
// we use 'ev_io' since the 'socket' can be treated as a file descriptor.
struct ev_io* io = malloc(sizeof(ev_io));
ev_io_init(io, accept_cb, socket, EV_READ);
ev_io_start(loop, io);
...

void accept_cb(struct ev_loop* loop, struct ev_io* io, int r)
{
    // someone has connected. we accept the child.
    struct sockaddr_un client_address;
    socklen_t client_address_len = sizeof(client_address);
    int client_fd = accept(socket, (sockaddr*)(&client_address),
                           &client_address_len);

    // 'read' / 'recv' from client_fd here.
    // or use another 'ev_io' for async read.
}

libevent should be similar.

jørgensen
  • 10,149
  • 2
  • 20
  • 27
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • Hi, many thanks for that information. Very useful indeed. I'm going to try and get it compiling. I'm very new to libev and/or libevent and it will take a bit of effort to pad out your code and get it working! – Eamorr Jan 27 '12 at 10:11
  • Hi KennyTM - what type is the third paramater, 'socket', of eve_io_init(...)? – Eamorr Jan 27 '12 at 10:49
  • @Eamorr: `int`. Please check the doc. http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_io_code_is_this_file_descrip – kennytm Jan 27 '12 at 12:32
  • thanks for the tip. I can't make much sense of this... Please bear in mind that I'm very new to libev. – Eamorr Jan 27 '12 at 12:34
  • Libevent can indeed monitor unix sockets too. (I'm not sure what part of the documentation seems to say it needs an IP/Port.) – nickm Jan 28 '12 at 15:22