linux local socket communication

Local socket communication

Use local socket, it can also be inter-process communication.

Local named pipes and sockets are the same as using a pseudo-file

Pipeline file type is p

Local socket file type is s.

When the call to bind function, it will generate local socket file corresponding camouflage

srwxr-xr-x 1 ys ys     0 7月   2 10:55 server.socket
srwxr-xr-x 1 ys ys     0 7月   2 10:55 client.socket

And network sockets different places:

  • Structure used is not the same, using the local socket:
struct sockaddr_un{
    sun_family;//AF_LOCAL
    sun_path;//本地套接字对应的伪装文件的名字,可以加路径
}
  • Customers must call the bind function
  • Need the header file: sys / un.h
  • Need to be removed in advance camouflage file generated by the implementation of the last, if not removed, then, bind function fails, the error message: Address already in use

Examples receiving end:

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

int main(){
  int fd = socket(AF_LOCAL, SOCK_STREAM, 0);
  
  unlink("server.socket");
  
  struct sockaddr_un serv;
  strcpy(serv.sun_path, "server.socket");
  serv.sun_family = AF_LOCAL;
  int ret = bind(fd, (struct sockaddr*)&serv, sizeof(serv));
  if(ret == -1){
    perror("bind error");
    exit(1);
  }

  listen(fd, 64);

  struct sockaddr_un cli;
  socklen_t len;
  int cfd = accept(fd, (struct sockaddr*)&cli, &len);

  while(1){
    char buf[64];
    ret = recv(cfd, buf, sizeof(buf), 0);
    if(ret == -1){
      perror("recv error");
      exit(1);
    }
    else if(ret == 0){
      printf("client closed\n");
      close(cfd);
    }
    printf("clinet path:%s\n", cli.sun_path);
    write(STDOUT_FILENO, buf, ret);
  }

  close(cfd);
  close(fd);
}

Examples of the transmitting end:

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

int main(){
  int fd = socket(AF_LOCAL, SOCK_STREAM, 0);

  unlink("client.socket");
  
  struct sockaddr_un cli;
  strcpy(cli.sun_path, "client.socket");
  cli.sun_family = AF_LOCAL;
  if(bind(fd, (struct sockaddr*)&cli, sizeof(cli)) == -1){
    perror("bind cli error");
    exit(1);
  }
  

  struct sockaddr_un to;
  to.sun_family = AF_LOCAL;
  strcpy(to.sun_path, "server.socket");

  int ret = connect(fd, (struct sockaddr*)&to, sizeof(to));

  int cnt = 0;
  while(1){
    char buf[64] = {0};
    sprintf(buf, "cnt = %d", cnt++);
    int ret = send(fd, buf, sizeof(buf), 0);
    if(ret == -1){
      perror("send error");
      exit(1);
    }
    sleep(1);
  }
}

c / c ++ mutual learning QQ group: 877 684 253

I micro letter: xiaoshitou5854

Guess you like

Origin www.cnblogs.com/xiaoshiwang/p/11119455.html