Einführung in die Netzwerkprogrammierung:udpserver 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 UDP socket */
	printf("Starting UDP server on port %d - ", server_port);
	if ((fdc=socket(PF_INET6, SOCK_DGRAM, 0)) < 0) {
		perror("UDP 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 to port and ip interface */
	if (bind(fdc, (struct sockaddr*)&local, sizeof(local)) < 0) {
		perror("UDP bind error");
		exit(errno);
	}
	printf("success\n");
	rlen=sizeof(remote);

	while(1) {
		/* Wait for UDP data */
		while ((slen=recvfrom(fdc, string, sizeof(string), 0, (struct sockaddr*)&remote, &rlen))>0) {
			inet_ntop(AF_INET6, &remote.sin6_addr, straddr, sizeof(straddr));
			printf("Got UDP data from %s\n", straddr);
			/* 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));
			}
			sendto(fdc, string, slen, 0, (struct sockaddr*)&remote, rlen);
			printf("UDP connection closed\n");
		}
	}
}