AF_LOCAL本地通信

server

#include 
#include 
#include 

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

#define STREAM_SERVER_MSG_FILE "/tmp/local_server"

int main(int argc, char *argv[])
{
	int msg_fd = 0;
	struct sockaddr_un serv;
	struct sockaddr_in client_addr;
	socklen_t client_length = sizeof(client_addr);
	int clientfd = 0;
	int ret = 0;

	msg_fd = socket(AF_UNIX, SOCK_STREAM, 0);
	if(msg_fd < 0)
	{
		perror("socket error");
		return 0;
	}

	unlink(STREAM_SERVER_MSG_FILE);
	bzero(&serv, sizeof(serv));
	serv.sun_family = AF_LOCAL;
	strcpy(serv.sun_path, STREAM_SERVER_MSG_FILE);

	ret = bind(msg_fd, (struct sockaddr *)&serv, sizeof(serv));
	if(ret < 0)
	{
		close(msg_fd);
		perror("bind error");
		return 0;
	}

	ret = listen(msg_fd, 1);
	if(ret < 0)
	{
		close(msg_fd);
		perror("listen error");
		return 0;
	}

	while(1)
	{
		clientfd = accept(msg_fd, (struct sockaddr*)&client_addr, &client_length);
		if (clientfd > 0)
		{
			char buf[256];
			memset(&buf, 0, sizeof(buf));
			ret = recv(clientfd, &buf, sizeof(buf), 0);
			if(ret != sizeof(buf))
			{
				printf("\033[32m[%s:%d]\033[36m ret = %d\033[0m\n", __FUNCTION__, __LINE__, ret);
			}
			printf("\033[32m[%s:%d]\033[36m buf = [%s]\033[0m\n", __FUNCTION__, __LINE__, buf);

			close(clientfd);
		}
	}

	close(msg_fd);

	return 0;
}



client

#include 
#include 
#include 

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

#define STREAM_SERVER_MSG_FILE "/tmp/local_server"

int main(int argc, char *argv[])
{
	int ret;
	int sockfd;
	struct sockaddr_un serv;

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	if(sockfd < 0)
	{
		perror("socket error");
		return -1;
	}

	bzero(&serv, sizeof(serv));
	serv.sun_family = AF_UNIX;
	strcpy(serv.sun_path, STREAM_SERVER_MSG_FILE);

	ret = connect(sockfd, (struct sockaddr *)&serv, sizeof(serv));
	if(ret < 0)
	{
		close(sockfd);
		perror("connect error");
		return -3;
	}

	ret = send(sockfd, "test", 4, 0);
	if(ret != 4)
	{
		printf("\033[32m[%s:%d]\033[36m ret=%d\033[0m\n", __FUNCTION__, __LINE__, ret);
	}

	close(sockfd);

	return 0;
}

你可能感兴趣的:(AF_LOCAL本地通信)