Chinaunix首页 | 论坛 | 博客
  • 博客访问: 898844
  • 博文数量: 453
  • 博客积分: 7865
  • 博客等级: 少将
  • 技术积分: 5673
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:21
个人简介

时光荏苒..

文章分类
文章存档

2015年(46)

2014年(22)

2013年(68)

2012年(218)

2011年(99)

分类: C/C++

2011-11-17 13:44:52

使用UNIX Domain Socket的过程和网络socket十分相似,也要先调用socket()创建一个socket文件描述符,address family指定为AF_UNIX,type可以选择SOCK_DGRAM或SOCK_STREAM,protocol参数仍然指定为0即可。

UNIX Domain Socket与网络socket编程最明显的不同在于地址格式不同,用结构体sockaddr_un表示,网络编程的socket地址是IP地址加端口号,而UNIX Domain Socket的地址是一个socket类型的文件在文件系统中的路径,这个socket文件由bind()调用创建,如果调用bind()时该文件已存在,则bind()错误返回。

程序中的offsetof宏,它在stddef.h头文件中定义:

#define offsetof(TYPE, MEMBER) ((int)&((TYPE *)0)->MEMBER)

offsetof(struct sockaddr_un, sun_path)就是取sockaddr_un结构体的sun_path成员在结构体中的偏移,也就是从结构体的第几个字节开始是sun_path成员。想一想,这个宏是如何实现这一功能的?(先将TYPE类型的指针首地址设为0,然后取MEMBER成员的地址就是该成员在TYPE中的偏移数。)

服务器的accept模块,通过accept得到客户端地址也应该是一个socket文件,如果不是socket文件就返回错误码,如果是 socket文件,在建立连接后这个文件就没有用了,调用unlink把它删掉,通过传出参数uidptr返回客户端程序的user id。

accept函数:系统调用accept()比较起来有点复杂。在远程的主机可能试图使用connect()连接你使用
listen()正在监听的端口。但此连接将会在队列中等待,直到使用accept()处理它。调用accept()
之后,将会返回一个全新的套接口文件描述符来处理这个单个的连接
。这样,对于同一个连接
来说,你就有了两个文件描述符。原先的一个文件描述符正在监听你指定的端口,新的文件描
述符可以用来调用send()和recv()。

 

服务器段代码:

#include
#include
#include
#include
#include
#include
#include

 

#define QLEN 10
#define CLI_PATH    "/var/tmp/"      /* +5 for pid = 14 chars */

/*
 * Create a server endpoint of a connection.
 * Returns fd if all OK, <0 on error.
 */
int serv_listen(const char *name)
{
 int                 fd, len, err, rval;
 struct sockaddr_un  un;
 char pathname[30];
 /* create a UNIX domain stream socket */
 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  return(-1);
 sprintf(pathname,"%s%s",CLI_PATH,name);
 unlink(pathname);   /* in case it already exists */

 /* fill in socket address structure */
 memset(&un, 0, sizeof(un));
 un.sun_family = AF_UNIX;
// strcpy(un.sun_path, name);
 sprintf(un.sun_path, "%s%s", CLI_PATH, name);
 len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);


 /* bind the name to the descriptor */
 if (bind(fd, (struct sockaddr *)&un, len) < 0) {
  rval = -2;
  goto errout;
 }
 
 if (listen(fd, QLEN) < 0) { /* tell kernel we're a server */
  rval = -3;
  goto errout;
 }
 return(fd);

errout:
 err = errno;
 close(fd);
 errno = err;
 return(rval);
}

int serv_accept(int listenfd, uid_t *uidptr)
{
 int                 clifd, len, err, rval;
 time_t              staletime;
 struct sockaddr_un  un;
 struct stat         statbuf;
 int i;
 len = sizeof(un);
 if ((clifd = accept(listenfd, (struct sockaddr *)&un, &len)) < 0)
  return(-1);     /* often errno=EINTR, if signal caught */

 /* obtain the client's uid from its calling address */
 len -= offsetof(struct sockaddr_un, sun_path); /* len of pathname */
 un.sun_path[len] = 0;           /* null terminate */

printf("client path is :");
for(i = 0;i printf("%c",un.sun_path[i]);
printf("\n");
 if (stat(un.sun_path, &statbuf) < 0) {
  rval = -2;
  goto errout;
 }

 if (S_ISSOCK(statbuf.st_mode) == 0) {
  rval = -3;      /* not a socket */
  goto errout;
 }

 if (uidptr != NULL)
  *uidptr = statbuf.st_uid;   /* return uid of caller */
 unlink(un.sun_path);        /* we're done with pathname now */
 return(clifd);

errout:
 err = errno;
 close(clifd);
 errno = err;
 return(rval);
}

int main(void)
{
int listenfd;
int clientfd;
char read_chr;
char write_chr='S';
uid_t uid=100;

listenfd = serv_listen("server_socket2");
if(listenfd<0)
{
 printf("server : listen error quit with %d\n",listenfd);
 return -1;
}

printf("server wait for client connect!\n");

clientfd = serv_accept(listenfd,&uid);

if(clientfd<0)
{
 printf("server : accept error quit with %d\n",clientfd);
 return -1;
}

printf("server wait for uid %d data!\n",(int)uid);

while(1)
{
 read(clientfd,&read_chr,1);
 sleep(1);
 write(clientfd,&write_chr,1);
 printf("server read:%c\n",read_chr);
}

}

////////////////////////////////////////////////////////

以下是客户端的connect模块,与网络socket编程不同的是,UNIX Domain Socket客户端一般要显式调用bind函数,而不依赖系统自动分配的地址。客户端bind一个自己指定的socket文件名的好处是,该文件名可以包含客户端的pid以便服务器区分不同的客户端。

客户端代码:

#include
#include
#include
#include
#include
#include
#include


#define CLI_PATH    "/var/tmp/"      /* +5 for pid = 14 chars */

/*
 * Create a client endpoint and connect to a server.
 * Returns fd if all OK, <0 on error.
 */
int cli_conn(const char *name)
{
 int                fd, len, err, rval;
 struct sockaddr_un un;
 char server_path[30];
 /* create a UNIX domain stream socket */
 if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  return(-1);

 /* fill socket address structure with our address */
 memset(&un, 0, sizeof(un));
 un.sun_family = AF_UNIX;
 sprintf(un.sun_path, "%s%05d", CLI_PATH, getpid());
 len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);

 unlink(un.sun_path);        /* in case it already exists */
 if (bind(fd, (struct sockaddr *)&un, len) < 0) {
  rval = -2;
  goto errout;
 }

 /* fill socket address structure with server's address */
 memset(&un, 0, sizeof(un));
 un.sun_family = AF_UNIX;
 sprintf(server_path,"%s%s",CLI_PATH,name);
 strcpy(un.sun_path, server_path);
 len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
 if (connect(fd, (struct sockaddr *)&un, len) < 0) {
  rval = -4;
  goto errout;
 }
 return(fd);

errout:
 err = errno;
 close(fd);
 errno = err;
 return(rval);
}

int main(void)
{
 int connfd;
 
 connfd = cli_conn("server_socket2");
 printf("connfd is %d\n",connfd);
 if(connfd < 0)
 {
  printf("cli_conn error quit!\n");
  return -1;
 }
 
 char read_chr;
 char write_chr='C';

while(1)
{
 write(connfd,&write_chr,1);
 sleep(1);
 read(connfd,&read_chr,1);
 printf("client read:%c\n",read_chr);
}

}

------------------------------------

Modify for testing logger -u option:

  1. /* Socket server for testing logger -u option.
  2.  * 2011-11-17
  3.  */
  4. #include <stddef.h>
  5. #include <sys/socket.h>
  6. #include <sys/un.h>
  7. #include <errno.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <sys/stat.h>


  11. #define QLEN 10
  12. #define CLI_PATH "/var/tmp/"

  13. /*
  14.  * Create a server endpoint of a connection.
  15.  * Returns fd if all OK, <0 on error.
  16.  */
  17. int serv_listen(const char *name)
  18. {
  19.     int fd, len, err, rval;
  20.     struct sockaddr_un un;
  21.     char pathname[30];
  22.     /* create a UNIX domain stream socket */
  23.     if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
  24.         return(-1);
  25.     
  26.     sprintf(pathname,"%s%s",CLI_PATH,name);
  27.     unlink(pathname); /* in case it already exists */

  28.     /* fill in socket address structure */
  29.     memset(&un, 0, sizeof(un));
  30.     un.sun_family = AF_UNIX;
  31.     // strcpy(un.sun_path, name);
  32.     sprintf(un.sun_path, "%s%s", CLI_PATH, name);
  33.     
  34.     len = offsetof(struct sockaddr_un, sun_path) + strlen(un.sun_path);
  35.     /* bind the name to the descriptor */
  36.     if (bind(fd, (struct sockaddr *)&un, len) < 0) {
  37.         rval = -2;
  38.         goto errout;
  39.     }

  40.     if (listen(fd, QLEN) < 0) { /* tell kernel we're a server */
  41.         rval = -3;
  42.         goto errout;
  43.     }
  44.     return(fd);

  45. errout:
  46.     err = errno;
  47.     close(fd);
  48.     errno = err;
  49.     return(rval);
  50. }

  51. int serv_accept(int listenfd, uid_t *uidptr)
  52. {
  53.     int clifd, len, err, rval;
  54.     time_t staletime;
  55.     struct sockaddr_un un;
  56.     struct stat statbuf;
  57.     int i;
  58.     len = sizeof(un);
  59.     if ((clifd = accept(listenfd, (struct sockaddr *)&un, &len)) < 0)
  60.         return(-1); /* often errno=EINTR, if signal caught */

  61.     /* obtain the client's uid from its calling address */
  62. /*    len -= offsetof(struct sockaddr_un, sun_path);
  63.     un.sun_path[len] = 0;

  64.     printf("client path is :");
  65.     for(i = 0;i<len;i++)
  66.         printf("%c",un.sun_path[i]);
  67.     printf("\n");
  68.     if (stat(un.sun_path, &statbuf) < 0) {
  69.         rval = -2;
  70.         goto errout;
  71.     }

  72.     if (S_ISSOCK(statbuf.st_mode) == 0) {
  73.         rval = -3;
  74.         goto errout;
  75.     }

  76.     if (uidptr != NULL)
  77.         *uidptr = statbuf.st_uid;
  78.     unlink(un.sun_path); */
  79.     return(clifd);

  80. errout:
  81.     err = errno;
  82.     close(clifd);
  83.     errno = err;
  84.     return(rval);
  85. }

  86. int main(void)
  87. {
  88.     int listenfd;
  89.     int clientfd;
  90.     char read_chr[50];
  91.     char write_chr='S';
  92.     uid_t uid=100;

  93.     listenfd = serv_listen("varzlg");
  94.     if(listenfd<0)
  95.     {
  96.         printf("server : listen error quit with %d\n",listenfd);
  97.         return -1;
  98.     }

  99.     printf("server waiting....\n");

  100.     clientfd = serv_accept(listenfd,&uid);

  101.     if(clientfd<0)
  102.     {
  103.         printf("server : accept error quit with %d\n",clientfd);
  104.         return -1;
  105.     }

  106.     printf("server wait for client: %d data!\n",clientfd);

  107.     read(clientfd,&read_chr,49);
  108.     printf("server read:%s\n",read_chr);

  109. }

修改:对照logger.c文件,并没有通常客户端的bind,也就没有id。因为不能修改logger.c

server端只能去掉uid部分。并修改了read函数buff大小。去掉了while循环,因为读取一次即可。
阅读(1243) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~