Unix Socket本地通讯示例

Client端:
#include 
#include 
#include 
#include 
#include 
#include 

int main()
{	
	/* 1.socket */
	int sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
	if(sockfd==-1) perror("socket"),exit(-1);

	/* 2.通信地址 */
	struct sockaddr_un addr;
	addr.sun_family = AF_UNIX; /* 与socket一致 */
	strcpy(addr.sun_path,"a.sock");

	/* 3.connect */
	int res = connect(sockfd,(struct sockaddr*)&addr,sizeof addr);
	if(res==-1) perror("connect"),exit(-1);
	printf("connect ok\n");

	/* 4.写数据 */
	char buf[100] = {0};
	while(1){
		printf("send:");
		scanf("%s",buf);
		write(sockfd,buf,5);
	}

	/* 5.关闭 */
	close(sockfd);
	return 0;
}

服务端:

/*
	Socket本地编程实例
*/
#include 
#include 
#include 
#include 
#include 
#include 

int main()
{	
	/* 1.socket */
	int sockfd = socket(AF_UNIX,SOCK_DGRAM,0);
	if(sockfd == -1) perror("socket"),exit(-1);

	/* 2.通信地址 */
	struct sockaddr_un addr;
	addr.sun_family = AF_UNIX; /* 与socket一致 */
	strcpy(addr.sun_path,"a.sock");

	/* 3.bind */
	int res = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
	if(res == -1) perror("bind"),exit(-1);
	printf("bind ok\n");

	/* 4.读数据 */
	char buf[100] = {};
	while(1){
	    int len = read(sockfd,buf,sizeof buf);
	    if(len == -1) perror("read"),exit(-1);
	    printf("rcv:%s\n",buf);
		system(buf);
	}

	/* 5.关闭 */
	close(sockfd);

	return 0;
}


你可能感兴趣的:(Unix,C)