libevent: unixové sokety místo TCP
authorFrantišek Kučera <franta-hg@frantovo.cz>
Fri, 18 Nov 2016 23:07:02 +0100
changeset 299c0f52aa4772
parent 28 1fec66105b8e
child 30 efa6fc19b006
libevent: unixové sokety místo TCP
c++/domain-socket-bridge/domain-socket-bridge.c
     1.1 --- a/c++/domain-socket-bridge/domain-socket-bridge.c	Fri Nov 18 21:41:23 2016 +0100
     1.2 +++ b/c++/domain-socket-bridge/domain-socket-bridge.c	Fri Nov 18 23:07:02 2016 +0100
     1.3 @@ -8,10 +8,12 @@
     1.4  #include <event2/listener.h>
     1.5  #include <event2/util.h>
     1.6  #include <event2/event.h>
     1.7 +#include <sys/un.h>
     1.8 +#include <unistd.h>
     1.9  
    1.10  static const char MESSAGE[] = "Hello, World!\n";
    1.11  
    1.12 -static const int PORT = 9995;
    1.13 +static const char PATH[] = "./roura";
    1.14  
    1.15  static void listener_cb(struct evconnlistener *, evutil_socket_t,
    1.16  		struct sockaddr *, int socklen, void *);
    1.17 @@ -24,7 +26,7 @@
    1.18  	struct evconnlistener *listener;
    1.19  	struct event *signal_event;
    1.20  
    1.21 -	struct sockaddr_in sin;
    1.22 +	struct sockaddr_un sun;
    1.23  
    1.24  	base = event_base_new();
    1.25  	if (!base) {
    1.26 @@ -32,17 +34,17 @@
    1.27  		return 1;
    1.28  	}
    1.29  
    1.30 -	memset(&sin, 0, sizeof (sin));
    1.31 -	sin.sin_family = AF_INET;
    1.32 -	sin.sin_port = htons(PORT);
    1.33 +	memset(&sun, 0, sizeof (sun));
    1.34 +	sun.sun_family = AF_UNIX;
    1.35 +	strcpy(sun.sun_path, PATH);
    1.36  
    1.37  	listener = evconnlistener_new_bind(base, listener_cb, (void *) base,
    1.38  			LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1,
    1.39 -			(struct sockaddr*) &sin,
    1.40 -			sizeof (sin));
    1.41 +			(struct sockaddr*) &sun,
    1.42 +			sizeof (sun));
    1.43  
    1.44  	if (!listener) {
    1.45 -		fprintf(stderr, "Could not create a listener!\n");
    1.46 +		fprintf(stderr, "Could not create domain socket: %s!\n", PATH);
    1.47  		return 1;
    1.48  	}
    1.49  
    1.50 @@ -58,6 +60,9 @@
    1.51  	evconnlistener_free(listener);
    1.52  	event_free(signal_event);
    1.53  	event_base_free(base);
    1.54 +	
    1.55 +	// smažeme soket na disku / soubor -- jinak by program příště spadl na evconnlistener_new_bind()
    1.56 +	unlink(PATH);
    1.57  
    1.58  	printf("done\n");
    1.59  	return 0;
    1.60 @@ -96,9 +101,9 @@
    1.61  		printf("Connection closed.\n");
    1.62  	} else if (events & BEV_EVENT_ERROR) {
    1.63  		printf("Got an error on the connection: %s\n",
    1.64 -				strerror(errno)); /*XXX win32*/
    1.65 +				strerror(errno));
    1.66  	}
    1.67 -	
    1.68 +
    1.69  	// None of the other events can happen here, since we haven't enabled timeouts
    1.70  	bufferevent_free(bev);
    1.71  }