Return to Tech/unix
Return to Tech/unix/bsdsock

#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/wait.h>

int SvrSock(char *port) {
	int sock, portnumber, opt;
	struct servent *se;
	struct sockaddr_in my;

	memset((char *)&my, 0, sizeof(my));
	my.sin_family = AF_INET;
	my.sin_addr.s_addr = htonl(INADDR_ANY);

	portnumber = atoi(port);
	my.sin_port = htons(portnumber);

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

	opt = 1;

	if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(int)) != 0) {
		perror("setsockopt error");
		close(sock);
		return -1;
	}

	if(bind(sock, (struct sockaddr *)&my, sizeof(my)) == -1 ) {
		perror("bind error");
		close(sock);
		return -1;
	}

	if(listen(sock, SOMAXCONN) == -1 ) {
		perror("listen error");
		close(sock);
		return -1;
	}

	return(sock);
}

int AcceptLoop(int sock) {
	int acc, len;

	struct sockaddr_in from;

	while(1) {
		len = sizeof(from);

		acc = accept(sock, (struct sockaddr *)&from, &len);
		if(acc < 0) {
			if(errno != EINTR) {
				perror("accept error");
			}
		} else {
			fprintf(stderr, "accept:%s:%d\n", inet_ntoa(from.sin_addr),
				ntohs(from.sin_port));

			SendRecv(acc);

			close(acc);

			acc = 0;
		}
	}

	return(0);
}

int SendRecv(int acc) {
	char buf[512], *ptr;
	int len;

	while(1) {
		if((len = recv(acc, buf, sizeof(buf), 0)) < 0) {
			perror("recv error");
			break;
		}

		if(len == 0) {
			fprintf(stderr, "recv:EOF\n");
			break;
		}

		buf[len] = '\0';

		if((ptr = strpbrk(buf, "\r\n")) != NULL) {
			*ptr = '\0';
		}

		fprintf(stderr, "[client]%s\n", buf);

		strcat(buf, ":OK\r\n");

		len = strlen(buf);

		if((len = send(acc, buf, len, 0)) < 0) {
			perror("send error");
			break;
		}
	}

	return (0);
}

int main(int argc, char *argv[]) {
	int sock;

	if(argc <= 1) {
		fprintf(stderr, "Usage ./a.out portnumber\n");
		return(1);
	}

	sock = SvrSock(argv[1]);
	if(sock == -1) {
		fprintf(stderr, "SvrSock(%s):error\n", argv[1]);
		return (-1);
	}

	fprintf(stderr, "ready for accept\n");

	AcceptLoop(sock);

	close(sock);

	return (0);
}


Return to Tech/unix
Return to Tech/unix/bsdsock