-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlower.cpp
89 lines (73 loc) · 2.15 KB
/
lower.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream> // cout
#include <sys/socket.h> // socket(), bind(), sendto(), recvfrom()
#include <arpa/inet.h> // for sockaddr_in, inet_addr()
#include <netinet/in.h>
#include <stdlib.h> // for atoi(), exit()
#include <unistd.h> // for close()
#include <cstring> // for memset()
#include <csignal>
#include "udp_serv.h" // initSock()
using namespace std;
int serverSock; /// server socket
/**
* Handles incoming signals
*
* @param sig the signal code that this process receives
*/
void signalHandler ( int sig ){
close(serverSock);
exit(0);
}
int main(int argc, char *argv[])
{
/* Assign signal handler */
signal(SIGTERM, signalHandler);
signal(SIGINT, signalHandler);
signal(SIGKILL, signalHandler);
struct sockaddr_in serverAddr;
struct sockaddr_in clientAddr;
unsigned int len = sizeof(serverAddr);
char inBuffer[MAX_MSG_LEN];
char outBuffer[MAX_MSG_LEN];
int bytesRcv;
if ( argc != 2)
{
cerr << "Usage: " << argv[0] << " <Port num>" << endl;
}
/* Initializing server socket */
int initSock = init_servSock(serverSock, atoi(argv[1]), &serverAddr);
if ( initSock < 0 )
{
cout << "UDP lower: could not initialize socket" << endl;
exit(-1);
}
/* Run forever until a terminate signal arrives */
while (1)
{
/* Clearing buffers */
memset(&inBuffer, 0, MAX_MSG_LEN);
memset(&outBuffer, 0, MAX_MSG_LEN);
/* Receive data from clients */
bytesRcv = recvfrom(serverSock, inBuffer, 1024, 0, (struct sockaddr*) &clientAddr, &len);
if ( bytesRcv < 0 ) {
cerr << "UDP lower: recvfrom() failed, or connection closed" << endl;
exit(-1);
}
/* lower case all upper cased letter */
int i;
int n = strlen(inBuffer);
for (i=0; i < n; i++)
{
inBuffer[i] = tolower(inBuffer[i]);
}
inBuffer[n] = 0;
cout << "UDP lower Client " << inet_ntoa(clientAddr.sin_addr) << ":" << clientAddr.sin_port << ": " << inBuffer << endl;
/* Sent data back to client */
sendto(serverSock, inBuffer, bytesRcv, 0, (struct sockaddr *) &clientAddr, len);
/* Clearing buffer */
memset(&inBuffer, 0, MAX_MSG_LEN);
memset(&outBuffer, 0, MAX_MSG_LEN);
}
close(serverSock);
return 0;
}