`
memorymyann
  • 浏览: 266753 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

18.unix域协议

阅读更多

UNIX域协议并不是一个真正的协议族,它是用在同一台主机上进行客户服务器通信时,能够使用和不同主机上通信相同的API的一种方法。所以它只是用在同一台主机上2个进程间的通信,当然同一主机上2个进程通信的方式在unix下面有:信号,管道,共享内存。

 

unix域地址结构

struct sockaddr_un{

  uint8_t sun_len;

  sa_family_t sun_family;

  char sun_path[104];

 //与网络通信不同,网络中双方确认需要IP和端口号,而在同一台机器上的2个进程则不需要这么麻烦,如果写过管道通信的例子,则这里类似于管道,需要定义是一个用于通信的文件(不能是系统中已有的文件)

};

 

样例:

 

服务器

#include "/programe/net/head.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/select.h"
#include "sys/un.h"  //定义了unix域的头文件

int main(int argc, char ** argv) {
        int sockfd;
        socklen_t len;
        struct sockaddr_un addr;

        sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);

//第一个参数为AF_LOCAL表示使用unix域协议,如果是SOCK_STREAM则后面相当类似于TCP,如果是DGRAM则类似于UDP协议
        bzero(&addr, sizeof(struct sockaddr_un));
        addr.sun_family = AF_LOCAL;

        strncpy(addr.sun_path, argv[1], sizeof(addr.sun_path) - 1);

//之前数据结构出有说明,这里是将输入参数的文件拷贝如addr.sun_path
        int flag = bind(sockfd, (struct sockaddr *)&addr, SUN_LEN(&addr));
        if(flag == -1) {
                printf("bind socket error\n");
                exit(1);
        }

        listen(sockfd, 10);
        int connfd = accept(sockfd, NULL, NULL);
        char buf[101];
        int n = read(connfd, buf, 100);
        buf[n] = '\0';
        printf("get message:%s\n", buf);
        close(connfd);
        close(sockfd);
}

 

客户端

#include "/programe/net/head.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "sys/select.h"
#include "sys/un.h"

int main(int argc, char ** argv) {
        int sockfd;
        socklen_t len;
        struct sockaddr_un addr;

        sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
        bzero(&addr, sizeof(struct sockaddr_un));
        addr.sun_family = AF_LOCAL;
        strncpy(addr.sun_path, argv[1], sizeof(addr.sun_path) - 1);

        connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_un));
        char buf[] = "hello world";
        write(sockfd, buf, sizeof(buf));
        close(sockfd);
        exit(0);
}

 

与TCP运行不同,服务器和客户运行指令如下

server /programe/net/mytemp.tmp

client /programe/net/mytemp.tmp

很像管道通信,2个文件必须一致(一至才能互相通信),并且文件不会被删除。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics