• 周三. 6月 29th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

unix domain socket的用法

admin

11月 28, 2021

服务器程序

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

#define SV_SOCK_PATH "/tmp/us_xfr"
#define BUF_SIZE 100
#define BACKLOG 5

int main() {
    struct sockaddr_un addr;
    int sfd, cfd;
    ssize_t numRead;
    char buf[BUF_SIZE];

    sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if(sfd == -1) {
        fprintf(stderr, "socket error");
        return -1;
    }
    if(remove(SV_SOCK_PATH) == -1 && errno != ENOENT) {
        fprintf(stderr, "remove /tmp/us_xfr");
        return -1;
    }
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SV_SOCK_PATH, sizeof(addr.sun_path)-1);
    if(bind(sfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_un)) == -1) {
        fprintf(stderr, "bind error.");
        return -1;
    }

    if(listen(sfd, BACKLOG) == -1) {
        fprintf(stderr, "listen error");
        return -1;
    }

    for(;;) {
        cfd = accept(sfd, NULL, NULL);
        if(cfd == -1) {
            fprintf(stderr, "accept error.");
            return -1;
        }

        while((numRead = read(cfd, buf, BUF_SIZE)) > 0) {
            if(write(STDOUT_FILENO, buf, numRead) != numRead) {
                fprintf(stderr, "write error.");
                return -1;
            }
        }
        if(numRead == -1) {
            fprintf(stderr, "read error.");
            return -1;
        }
        if(close(cfd) == -1) {
            fprintf(stderr, "close error.");
            return -1;
        }
    }

    return 0;
}

客户端代码

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

#define SV_SOCK_PATH "/tmp/us_xfr"
#define BUF_SIZE 100

int main() {
    struct sockaddr_un addr;
    int sfd;
    ssize_t numRead;
    char buf[BUF_SIZE];

    sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if(sfd == -1) {
        fprintf(stderr, "socket error");
        return -1;
    }

    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, SV_SOCK_PATH, sizeof(addr.sun_path)-1);

    if(connect(sfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
        fprintf(stderr, "connect error.");
        return -1;
    }

    while((numRead=read(STDIN_FILENO, buf, BUF_SIZE)) > 0) {
        if(write(sfd, buf, numRead) != numRead) {
            fprintf(stderr, "partial/failed write");
            return -1;
        }
    }

    if(numRead == -1) {
        fprintf(stderr, "read error");
        return -1;
    }
    return 0;
}

发表评论

您的电子邮箱地址不会被公开。