程式語言 - GNU - C/C++ - Domain Socket



參考資訊:
https://troydhanson.github.io/network/Unix_domain_sockets.html

Domain Socket不需要使用Port且是透過File System機制做傳輸

server.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int cl = 0;
    int fd = -1;
    char buf[255] = {0};
    struct sockaddr_un addr = {0};
    const char *path = "./domain_socket";

    unlink(path);
    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, path);
    bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    listen(fd, 5);

    cl = accept(fd, NULL, NULL);
    while (read(cl, buf, sizeof(buf))) {
        printf("read: \"%s\"\n", buf);
    }
    close(cl);
    return 0;
}

client.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int fd = -1;
    char buf[255] = {"I am error !"};
    struct sockaddr_un addr = {0};

    fd = socket(AF_UNIX, SOCK_STREAM, 0);
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, "./domain_socket");
    connect(fd, (struct sockaddr *)&addr, sizeof(addr));
    write(fd, buf, strlen(buf));
    close(fd);
    return 0;
}

編譯、執行

$ gcc server.c -o server
$ gcc client.c -o client

$ ./server&

$ ls -al ./domain_socket
    srwxr-xr-x 1 steward steward 0 Dec  1 01:21 domain_socket

$ ./client
    read: "I am error !"