Einführung in die Netzwerkprogrammierung:tcpserver v6.c

aus PUG, der Penguin User Group
Wechseln zu: Navigation, Suche
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __hpux
#include <unistd.h>
#include <arpa/inet.h>
#include <ctype.h>
#endif
#ifdef __sun
#include <unistd.h>
#include <arpa/inet.h>
#include <ctype.h>
#endif

#define MAX_STRING_SIZE 1024

int main (int argc, char ** argv) {
	int fdc, fdd;
	char string[MAX_STRING_SIZE], *p;
	struct sockaddr_in6 local, remote;
	int server_port, slen;
#ifdef __hpux
	int rlen;
#else
	socklen_t rlen;
#endif
	socklen_t * addr_len;
	int * addr_fam;
	char straddr[INET6_ADDRSTRLEN];

	/* Check for arguments - portnumber required */
	if (argc<2) {
		printf("Too few arguments\n");
		printf("Usage: %s <port>\n\n", argv[0]);
		exit(1);
	}
	server_port=atoi(argv[1]);
	if ((server_port==0) || (server_port>65535)) {
		printf("Invalid port number\n");
		exit(1);
	}

	/* Open TCP socket */
	printf("Starting TCP server on port %d - ", server_port);
	if ((fdc=socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
		perror("TCP socket error");
		exit(errno);
	}

       local.sin6_family=AF_INET6; 			/* IPv6 */
	local.sin6_port=htons(server_port); 	/* listen on port <server_port> */
	local.sin6_addr=in6addr_any;			/* listen on any ip interface */
	
	/* Bind and listen on port and ip interface */
	if (bind(fdc, (struct sockaddr*)&local, sizeof(local)) < 0) {
		perror("TCP bind error");
		exit(errno);
	}
	if (listen(fdc, 15) < 0) {
		perror("TCP listen error");
		exit(errno);
	}
	printf("success\n");

	while(1) {
  	rlen=sizeof(remote);
	/* Accept connections */
	if ((fdd=accept(fdc, (struct sockaddr*)&remote, &rlen)) < 0) {
		perror("accept error");
		exit(errno);
	}
	/* Create child to be able to get multiple connections */
	switch(fork()) {
		case -1: 
			perror("fork error");
			exit(errno);
		case 0:
			/* Child process: read TCP data */
			close(fdc);
			inet_ntop(AF_INET6, &remote.sin6_addr, straddr, sizeof(straddr));
			printf("Got TCP-Connection from %s\n", straddr);
			while ((slen=read(fdd, string, sizeof(string)))>0) {
				/* Whatever you want to do with the data...
				in this case we just convert it and send it back */
				for (p=string; p<string+slen; p++) {
					if (isalpha(*p)) *p=(islower(*p) ? toupper(*p) : tolower(*p));
				}
				write(fdd, string, slen);
			}
			printf("TCP-Connection closed\n");
			exit(0);
		default:
			/* Parent process: prepare for new connections */
			close(fdd);
			break;
		}
	}
}