Einführung in die Netzwerkprogrammierung:udpserver.c

aus PUG, der Penguin User Group
Wechseln zu: Navigation, Suche
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

#define MAX_STRING_SIZE 1024

int main (int argc, char ** argv) {
	int fdc, fdd;
	char string[MAX_STRING_SIZE], *p;
	struct sockaddr_in local, remote;
	int server_port, rlen, slen;

	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) {
		printf("invalid port number\n");
		exit(1);
	}

	// open udp socket
	printf("Starting UDP server on port %d - ", server_port);
	if ((fdc=socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("udp socket error");
		exit(errno);
	}

	local.sin_family=AF_INET;
	// listen on port <server_port>
	local.sin_port=htons(server_port);
	// listen on any ip interface
	local.sin_addr.s_addr=htonl(INADDR_ANY);
	memset(&local.sin_zero, 0, sizeof(local.sin_zero));

	// 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) {
			printf("Got UDP data from %s\n", inet_ntoa(remote.sin_addr));
			// 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");
		}
	}
}