-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.c
107 lines (80 loc) · 2.43 KB
/
server.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#define QSIZE 5
#define BSIZE 256
#define SOCKET_ADDRESS "mysocket"
/*
* Convert a null-terminated sting (one whose end is denoted by a byte
* containing '\0') to all upper case letters by starting at the
* beginning and going until the null byte is found.
*/
void convert_string (char *cp)
{
char *currp; /* pointer to current position in the input string */
int c; /* return value of toupper is the converted letter */
for (currp = cp; *currp != '\0'; currp++) {
c = toupper (*currp);
*currp = (char) c;
}
}
int main(int argc, char *argv[])
{
int handshake_sockfd, session_sockfd, ret;
struct sockaddr_un saun;
char buf[BSIZE];
#if 1
/* Add Code: Populate the sockaddr_un struct */
strcpy(saun.sun_path, SOCKET_ADDRESS);
saun.sun_family = AF_UNIX;
/* Add Code: Create the handshake socket */
handshake_sockfd = socket(PF_UNIX, SOCK_STREAM, 0);
if (handshake_sockfd < 0) {
perror("Error Opening Socket");
return EXIT_FAILURE;
}
/*
* We need to unlink the address before binding to ensure the
* address is free before attempting to bind.
*/
unlink(SOCKET_ADDRESS);
/* Add Code: Bind the handshake socket to the sockaddr. */
ret = bind(handshake_sockfd, (struct sockaddr *) &saun, sizeof(saun));
if (ret < 0) {
perror("Error Binding Socket");
return EXIT_FAILURE;
}
/* Add Code: Make the handshake socket a listening socket, with a
* specified Queue Size
*/
ret = listen(handshake_sockfd, 2);
if (ret < 0) {
perror("Error Listening on Socket");
return EXIT_FAILURE;
}
/* Add Code: Accept a connection on the handshake socket,
* giving the session socket as the return value.
*/
session_sockfd = accept(handshake_sockfd, NULL, NULL);
if (session_sockfd < 0) {
perror("Error Accepting Socket");
return EXIT_FAILURE;
}
/* Add Code: Read lines one at a time from the connected session
* socket. Convert each line to uppercase using convert_string, and
* write the line back to the client. Continue until there are no
* more lines to read.
*/
while (read(session_sockfd, buf, BSIZE) > 0) {
printf("RECEIVED:\n%s", buf);
convert_string(buf);
printf("SENDING:\n%s\n", buf);
write(session_sockfd, buf, BSIZE);
}
close(session_sockfd);
close(handshake_sockfd);
#endif
}