接收程序 recv.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#define PATH "/home/wenhao/unixdomain"
int main(int argc ,char *argv[])
{
int sockfd = 0;
struct sockaddr_un addr;
unlink(PATH);
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,PATH);
unsigned int len = strlen(addr.sun_path) + sizeof(addr.sun_family);
sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
if(sockfd < 0 )
{
perror("socket error");
exit(-1);
}
if(bind(sockfd,(struct sockaddr *)&addr,len) < 0)
{
perror("bind error");
close(sockfd);
exit(-1);
}
printf("Bind is ok\n");
while(1)
{
char recv_buf[20] = "";
recvfrom(sockfd,recv_buf,sizeof(recv_buf),0,(struct sockaddr*)&addr,&len);
printf("Recv: %s\n",recv_buf);
}
return 0;
}
发送程序 send.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/un.h>
#define PATH "/home/wenhao/unixdomain"
int main(int argc,char *argv[])
{
int sockfd = 0;
struct sockaddr_un addr;
bzero(&addr,sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,PATH);
sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
if(sockfd < 0)
{
perror("socket error");
exit(-1);
}
while(1)
{
static int counter = 0;
char send_buf[20] = "";
counter++;
sprintf(send_buf,"Counter is %d",counter);
int len = strlen(addr.sun_path)+sizeof(addr.sun_family);
sendto(sockfd,send_buf,strlen(send_buf),0,(struct sockaddr*)&addr,len);
printf("Send: %s\n",send_buf);
sleep(1);
}
return 0;
}
注意:使用unix domain socket,不管是tcp方式还是udp方式,客户端的socket都必须先进行bind操作!否则客户端无法向服务器端正常发送数据。