#include //printf #include //memset, strtok #include //exit(0); #include #include #include //close() #include "udpserver.h" #include "sound.h" #include "config.h" #define BUFLEN 512 //Max length of buffer //#define PORT 8888 void die(char *s) { perror(s); //exit(1); } void udpserver(void) { struct sockaddr_in si_me, si_other; int PORT = cfgreadudpport(); int s, slen = sizeof(si_other) , recv_len; char buf[BUFLEN]; //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); } // zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) { die("bind"); } //keep listening for data while(1) { memset(buf,'\0', BUFLEN); //try to receive some data, this is a blocking call if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, (unsigned int *)&slen)) == -1) { die("recvfrom()"); } //print details of the client/peer and the data received printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); printf("Data: %s\n" , buf); if (!processUDPInput(buf)) { break; } } close(s); } int processUDPInput(char *input) { /** * Returns 0 on exit * Return 1 on success */ if (strcmp(input, "exit") == 0) { return 0; } playSound(lookupSounds(input[0])); return 1; } //Client part void sendKeyUDP(char *server, char *message) { struct sockaddr_in si_other; int s, slen=sizeof(si_other); int PORT = cfgreadudpport(); if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); } memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(server , &si_other.sin_addr) == 0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } //send the message if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1) { die("sendto()"); } close(s); }