/* test_sockets.c */ #include #include #include #include #include #include #include #include typedef enum { FALSE, TRUE } Boolean; #define SOCK_PATH "test_sockets_socket" #define USE_SOCK_DGRAM //#undef USE_SOCK_DGRAM #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) int main(int argc, char *argv[]) { struct sockaddr_un addr = { 0 }; const char *path = SOCK_PATH; #ifdef USE_SOCK_DGRAM int sfd; int type = SOCK_DGRAM; #else int sfd, cfd; int type = SOCK_STREAM; #define LISTEN_BACKLOG 50 struct sockaddr_un peer_addr = { 0 }; socklen_t peer_addr_size; #endif /* Create a UNIX domain socket and bind it to 'path'. Return the socket descriptor on success, or -1 on error. */ /* Create socket bound to well-known address */ if (remove(SOCK_PATH) == -1 && errno != ENOENT) handle_error("remove-SOCK_PATH"); addr.sun_family = AF_UNIX; if (strlen(path) < sizeof(addr.sun_path)) strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); else handle_error("strncpy"); sfd = socket(AF_UNIX, type, 0); if (sfd == -1) handle_error("socket"); if (bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1) { close(sfd); handle_error("bind"); } /* Temporary test: make socket world readable */ //Does not work? chmod (path, S_IRUSR || S_IWUSR || S_IROTH || S_IWOTH); chmod (path, 0444); //chmod (path, 0644); //chmod (path, 0666); #ifdef USE_SOCK_DGRAM fprintf(stderr, "Receiving via datagram socket\n"); #else fprintf(stderr, "Receiving via stream socket\n"); if (listen(sfd, LISTEN_BACKLOG) == -1) handle_error("listen"); peer_addr_size = sizeof(struct sockaddr_un); cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_size); if (cfd == -1) handle_error("accept"); #endif exit(EXIT_SUCCESS); }