UNIX域套接字实例

/* ************************************************************************
 *       Filename:  recv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2011年12月03日 20时52分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#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;
}

 

发送:

/* ************************************************************************
 *       Filename:  send.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2011年12月03日 20时42分37秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#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;
}

 

posted @ 2011-12-03 21:10  hnrainll  阅读(3468)  评论(0编辑  收藏  举报