GNU >> C/C++

domain socket


參考資訊:
1. unix_domain_sockets

domain socket不需要使用port且是透過filesystem機制做傳輸

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 fd = -1, cl = 0;
    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 !"


返回上一頁