Last active
October 3, 2017 03:54
-
-
Save ph1ee/b96e7bba9b2363eb1668623188fa6940 to your computer and use it in GitHub Desktop.
testing abstract unix domain socket address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <sys/socket.h> | |
| #include <sys/un.h> | |
| #include <unistd.h> | |
| #include <stdlib.h> | |
| int create_abstract_socket(const char *name) { | |
| int sockfd = socket(AF_UNIX, SOCK_STREAM, 0); | |
| if (sockfd < 0) { | |
| return -1; | |
| } | |
| struct sockaddr_un addr; | |
| memset(&addr, 0, sizeof(addr)); | |
| addr.sun_family = AF_UNIX; | |
| addr.sun_path[0] = '\0'; | |
| strncpy(&addr.sun_path[1], name, sizeof(addr.sun_path) - 2); | |
| if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { | |
| close(sockfd); | |
| return -1; | |
| } | |
| return sockfd; | |
| } | |
| int main(int argc, char *argv[]) { | |
| int server = 0; | |
| int opt; | |
| while ((opt = getopt(argc, argv, "s")) != -1) { | |
| switch (opt) { | |
| case 's': | |
| server = 1; | |
| break; | |
| } | |
| } | |
| char name[32]; | |
| snprintf(name, sizeof(name), "%d", getpid()); | |
| int sockfd = create_abstract_socket(name); | |
| if (server) { | |
| if (sockfd < 0 || listen(sockfd, 1) < 0) { | |
| exit(EXIT_FAILURE); | |
| } | |
| fprintf(stdout, "listening at %s\n", name); | |
| int fd; | |
| struct sockaddr_un addr; | |
| memset(&addr, 0, sizeof(addr)); | |
| socklen_t addrlen = sizeof(addr); | |
| while ((fd = accept(sockfd, (struct sockaddr *)&addr, &addrlen)) > -1) { | |
| if (((struct sockaddr *)&addr)->sa_family != AF_UNIX) { | |
| fprintf(stderr, "unexpected socket type\n"); | |
| exit(EXIT_FAILURE); | |
| } | |
| fprintf(stdout, "connected from %s%s\n", | |
| addr.sun_path[0] == '\0' ? "@" : "", | |
| addr.sun_path[0] == '\0' ? &addr.sun_path[1] : addr.sun_path); | |
| close(fd); | |
| } | |
| } else { | |
| struct sockaddr_un addr; | |
| memset(&addr, 0, sizeof(addr)); | |
| addr.sun_family = AF_UNIX; | |
| addr.sun_path[0] = '\0'; | |
| strncpy(&addr.sun_path[1], argv[optind], sizeof(addr.sun_path) - 2); | |
| fprintf(stdout, "%s is connecting to %s\n", name, argv[optind]); | |
| if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) < 0) { | |
| exit(EXIT_FAILURE); | |
| } | |
| } | |
| exit(EXIT_SUCCESS); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment