1. 程式人生 > >socket程式設計UNIX協議

socket程式設計UNIX協議

//伺服器
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>

#define ERR_EXIT(m) \
	do \
	{ \
		perror(m);	\
		exit(EXIT_FAILURE);\
	}while(0)

void echo_srv(int conn)
{
	char recvbuf[1024] = {0};
	int n;
	while(1)
	{
		n = read(conn, recvbuf, sizeof(recvbuf));
		if(n==-1)
		{
			if(errno == EINTR)
				continue;
			ERR_EXIT("read");
		}
		else if(n==0)
		{
			printf("client close\n");
			break;
		}
		fputs(recvbuf, stdout);
		write(conn, recvbuf, strlen(recvbuf));
		memset(recvbuf, 0, sizeof(recvbuf));
	}
	close(conn);
}

int main(void)
{
	int listenfd;
	if((listenfd=socket(PF_UNIX, SOCK_STREAM, 0))<0)
		ERR_EXIT("socket");

	struct sockaddr_un servaddr;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, "test_socket");

	if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr))<0)
		ERR_EXIT("bind");

	if(listen(listenfd, SOMAXCONN)<0)
		ERR_EXIT("listen");
	int conn;
	while(1)
	{
		conn = accept(listenfd, NULL,NULL);
		if(conn ==-1)
		{
			if(errno == EINTR)
				continue;
			ERR_EXIT("accept");
		}

		pid=fork();
		if(pid==-1)
			ERR_EXIT("fork");
		if(pid==0)
		{
			close(listenfd);
			echo_srv(conn);
			exit(EXIT_SUCCESS);
		}
		close(conn);
	}
	return 0;
}

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>

#define ERR_EXIT(m) \
	do \
	{ \
		perror(m);	\
		exit(EXIT_FAILURE);\
	}while(0)

void echo_cli(int sock)
{
	char sendbuf[1024] ={0};
	char recvbuf[1024] = {0};
	while(fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
	{
		write(sock, sendbuf, strlen(sendbuf));
		read(sock, recvbuf, sizeof(recvbuf));
		fputs(recvbuf, stdout);
		memset(recvbuf, 0, sizeof(recvbuf));
		memset(sendbuf, 0, sizeof(sendbuf));
	}
	close(sock);
}

int main(void)
{
	int sock;
	if((sock= socket(PF_UNIX, SOCK_STREAM, 0))<0)
		ERR_EXIT("socket");
	
	unlink("test_socket");
	struct sockaddr_un servaddr;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sun_family = AF_UNIX;
	strcpy(servaddr.sun_path, "test_socket");

	if(connect(sock, (struct sockaddr*)&servaddr, sizeof(servaddr))<0)
		ERR_EXIT("connect");

	echo_cli();
	return 0;
}