Added getopt to select mode #1; Added udpserver #2

This commit is contained in:
2017-12-15 12:03:53 +01:00
parent 1afa4504ab
commit c298de57a8
10 changed files with 208 additions and 54 deletions

94
udpserver.c Normal file
View File

@@ -0,0 +1,94 @@
#include<stdio.h> //printf
#include<string.h> //memset, strtok
#include<stdlib.h> //exit(0);
#include<arpa/inet.h>
#include<sys/socket.h>
#include <unistd.h> //close()
#include "udpserver.h"
#include "sound.h"
#include "config.h"
#define BUFLEN 512 //Max length of buffer
//#define PORT 8888
#include "udpserver.h"
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)
{
//printf("Waiting for data...");
//fflush(stdout);
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;
}
//now reply the client with the same data
if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1)
{
die("sendto()");
}
}
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;
}