UNIX域套接字——UNIX domain socket(DGRAM)

#define UNIX_PATH_MAX    108

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <stdio.h>

#define BUFSIZE 32

int main(void)
{
	int sd;
	char buf[BUFSIZE];
	struct sockaddr_un hisend;
	int ret;

	sd = socket(PF_LOCAL, SOCK_DGRAM, 0);
	if (sd == -1) {
		perror("socket()");
		goto socket_err;
	}

	hisend.sun_family = AF_UNIX;
	snprintf(hisend.sun_path, UNIX_PATH_MAX, "rcv_sock");

	ret = connect(sd, (struct  sockaddr *)&hisend, sizeof(hisend));
	if (ret == -1) {
		perror("connect()");
		goto connect_err;
	}

	while (1) {
		ret = read(0, buf, BUFSIZE);
		/* if error */
		if (ret == 0) {
			break;
		}

		write(sd, buf, ret);
		ret = read(sd, buf, BUFSIZE);
		if (ret == -1) {
			perror("read(sd)");
			break;
		}
		write(1, buf, ret);
	}

	close(sd);

	return 0;



accept_err:
connect_err:
	close(sd);
socket_err:
	return 1;
}
#define UNIX_PATH_MAX    108

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <stdio.h>

#define BUFSIZE 32

int main(void)
{
	int sd;
	char buf[BUFSIZE];
	struct sockaddr_un myend, hisend;
	socklen_t hislen;
	int ret;

	sd = socket(PF_LOCAL, SOCK_DGRAM, 0);
	if (sd == -1) {
		perror("socket()");
		goto socket_err;
	}

	myend.sun_family = AF_UNIX;
	snprintf(myend.sun_path, UNIX_PATH_MAX, "rcv_sock");

	unlink(myend.sun_path);
	ret = bind(sd, (struct  sockaddr *)&myend, sizeof(myend));
	if (ret == -1) {
		perror("bind()");
		goto bind_err;
	}

	hislen = sizeof(hisend);
	while (1) {
		ret = recvfrom(sd, buf, BUFSIZE, 0, (struct sockaddr *)&hisend, &hislen);
		/* if error */
		if (ret == 0) {
			break;
		}

		write(1, buf, ret);
		ret = sendto(sd, "xxxxx\n", 6, 0, (struct sockaddr *)&hisend, hislen);
		if (ret == -1) {
			perror("write(sd)");
			break;
		}
	}

	close(sd);

	return 0;



bind_err:
	close(sd);
socket_err:
	return 1;
}



posted @ 2013-10-31 21:23  pangbangb  阅读(956)  评论(0编辑  收藏  举报