-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer4.c
More file actions
191 lines (170 loc) · 6.48 KB
/
Server4.c
File metadata and controls
191 lines (170 loc) · 6.48 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
/*
* Predefined time-zone offset table relative to Malaysia Standard Time (MST, UTC+8).
* - Each time zone is mapped to its corresponding offset from MST.
*/
struct timezone_offset {
const char *zone;
int offset; /* Offset in hours from Malaysia Standard Time */
};
const struct timezone_offset tz_table[] = {
{"PST", -16}, /* Pacific Standard Time (GMT-8 relative to MST+8) */
{"MST", -15}, /* Mountain Standard Time (GMT-7 relative to MST+8) */
{"CST", -14}, /* Central Standard Time (GMT-6 relative to MST+8) */
{"EST", -13}, /* Eastern Standard Time (GMT-5 relative to MST+8) */
{"GMT", -8}, /* Greenwich Mean Time (GMT+0 relative to MST+8) */
{"CET", -7}, /* Central European Time (GMT+1 relative to MST+8) */
{"MSK", -5}, /* Moscow Time (GMT+3 relative to MST+8) */
{"JST", +1}, /* Japan Standard Time (GMT+9 relative to MST+8) */
{"AEDT", +3}, /* Australian Eastern Daylight Time (GMT+11 relative to MST+8) */
{NULL, 0} /* Sentinel value to mark the end of the table */
};
/*
* Function to find the offset for a given time zone relative to MST.
* - If the time zone is valid, returns the corresponding offset in hours.
* - If the time zone is invalid, returns INT_MIN as an error flag.
*/
int find_timezone_offset(const char *zone) {
for (int i = 0; tz_table[i].zone != NULL; i++) {
if (strcmp(tz_table[i].zone, zone) == 0) {
return tz_table[i].offset;
}
}
return INT_MIN; /* Invalid time zone */
}
/*
* Function to get the current time in a specific time zone relative to MST.
* - Adjusts the time based on the given offset from MST.
* - Formats the adjusted time as a string.
*/
void get_time_in_timezone(char *buffer, size_t buffer_size, int offset) {
time_t now = time(NULL); /* Get the current time */
now += offset * 3600; /* Adjust time by offset (in seconds) */
struct tm *local_time = localtime(&now); /* Convert to adjusted time as local time */
/* Format the date and time into the provided buffer */
strftime(buffer, buffer_size, "%A, %d %B %Y %H:%M:%S\r\n", local_time);
}
int main(void) {
/*
* Initialize WinSock.
* - Required for using sockets on Windows.
* - MAKEWORD(2, 2) specifies version 2.2 of the API.
*/
WSADATA wsa_data;
if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) {
fprintf(stderr, "Failed to initialize WinSock.\n");
return 1;
}
/*
* Create a listening socket.
* - Configured for TCP/IP communication (SOCK_STREAM).
*/
SOCKET listen_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket == INVALID_SOCKET) {
fprintf(stderr, "Socket creation failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
/*
* Configure the server's address and port.
* - Use designated initializers for clarity and maintainability.
*/
struct sockaddr_in server_addr = {
.sin_family = AF_INET,
.sin_port = htons(8080), /* Convert port to network byte order */
.sin_addr.s_addr = INADDR_ANY /* Bind to all network interfaces */
};
/*
* Bind the listening socket to the specified address and port.
*/
if (bind(listen_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
fprintf(stderr, "Bind failed: %d\n", WSAGetLastError());
closesocket(listen_socket);
WSACleanup();
return 1;
}
/*
* Start listening for incoming connection requests.
* - SOMAXCONN allows the maximum number of pending connections.
*/
if (listen(listen_socket, SOMAXCONN) == SOCKET_ERROR) {
fprintf(stderr, "Listen failed: %d\n", WSAGetLastError());
closesocket(listen_socket);
WSACleanup();
return 1;
}
printf("[DEBUG] Server4 (Malaysia Time): Waiting for a client to connect...\n");
/*
* Accept a client connection.
* - If `accept()` fails, clean up and exit.
*/
SOCKET client_socket = accept(listen_socket, NULL, NULL);
if (client_socket == INVALID_SOCKET) {
fprintf(stderr, "Accept failed: %d\n", WSAGetLastError());
closesocket(listen_socket);
WSACleanup();
return 1;
}
printf("[DEBUG] Client connected.\n");
char buffer[1024];
for (;;) {
/*
* Receive data from the client.
* - If `recv()` returns <= 0, the client has disconnected.
*/
int n = recv(client_socket, buffer, (int)(sizeof(buffer) - 1), 0);
if (n <= 0) {
printf("[DEBUG] Client disconnected.\n");
break;
}
buffer[n] = '\0'; /* Null-terminate the received string */
/*
* Check for the "Time <zone>" command.
* - Extract the time zone from the command.
* - Return the current time in the specified time zone.
*/
if (strncmp(buffer, "Time ", 5) == 0) {
char zone[64];
sscanf(buffer + 5, "%63s", zone); /* Extract the time zone */
int offset = find_timezone_offset(zone);
if (offset != INT_MIN) {
char time_response[256];
get_time_in_timezone(time_response, sizeof(time_response), offset);
send(client_socket, time_response, (int)strlen(time_response), 0);
} else {
const char *error_msg = "Error: Invalid time zone.\r\n";
send(client_socket, error_msg, (int)strlen(error_msg), 0);
}
continue;
}
/*
* Check for the "Exit Server" command.
* - If received, terminate the connection and server.
*/
if (strcmp(buffer, "Exit Server") == 0) {
printf("[DEBUG] 'Exit Server' command received. Shutting down.\n");
break;
}
/*
* Send an error message for unrecognized commands.
*/
const char *error_msg = "Error: Unrecognized command. Use 'Time <zone>' or 'Exit Server'.\r\n";
send(client_socket, error_msg, (int)strlen(error_msg), 0);
}
/*
* Cleanup resources before exiting.
* - Close the client and listening sockets.
* - Terminate WinSock.
*/
closesocket(client_socket);
closesocket(listen_socket);
WSACleanup();
printf("[DEBUG] Server4 (Malaysia Time) shutdown complete.\n");
return 0;
}