网络编程5 本地套接字

本地套接字是进程间通信的一种方式,除了本地套接字外还有管道、消息队列等

lib/common.h

#ifndef __COMMON_H__
#define __COMMON_H__
#include <sys/socket.h>
#include <netdb.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <sys/un.h>
#endif

server.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/common.h"
#define MAXLINE 1024

int main() {
    int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    struct sockaddr_un server_addr, client_addr;
    server_addr.sun_family = AF_LOCAL;
    char* path = "/home/grape/test/test.sock";
    unlink(path);
    strcpy(server_addr.sun_path, path);
    if (bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        error(1, errno, "bind is error");
    }
    listen(sockfd, 0);
    int client_len = sizeof(client_addr);
    int fd;
    if ((fd = accept(sockfd, (struct sockaddr*)&client_addr, &client_len)) < 0) {
        error(1, errno, "accept is failed");
    }
    char buf[MAXLINE];
    while (1) {
        int n = read(fd, buf, MAXLINE);
        if (n == 0) {
            printf("client exit");
            break;
        }
        buf[n] = 0;
        printf("buf: %s\n", buf);
        strcpy(buf, "recived");
        if (write(fd, buf, strlen(buf)) != strlen(buf)) {
            error(1, errno, "write error");
        }
    }
    close(fd);
    close(sockfd);
    return 0;
}

client.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lib/common.h"
#define MAXLINE 1024

int main() {
    int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (sockfd < 0) {
        error(2, errno, "create socket failed!!");
    }
    struct sockaddr_un server_addr;
    server_addr.sun_family = AF_LOCAL;
    strcpy(server_addr.sun_path, "/home/grape/test/test.sock");
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        error(1, errno, "connect failed");
    }
    char buf[MAXLINE];
    while (scanf("%s", buf) != EOF) {
        if (write(sockfd, buf, strlen(buf)) != strlen(buf)) {
            error(1, errno, "write error");
        }
        int n = read(sockfd, buf, MAXLINE);
        if (n == 0) {
            error(1, errno, "server terminated prematurely");
        }
        buf[n] = 0;
        printf("ret: %s\n", buf);
    }
    return 0;
}

本地套接字使用SOCK_DGRAM的时候,使用和IPV4网络套接字相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值