-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.c
115 lines (100 loc) · 2.21 KB
/
util.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
108
109
110
111
112
113
114
115
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "util.h"
#ifdef _WIN32
#include <windows.h>
#endif
volatile sig_atomic_t stop = 0;
#ifdef _WIN32
BOOL WINAPI console_handler(DWORD signal_type) {
switch (signal_type) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
stop = 1;
return TRUE;
default:
return FALSE;
}
}
#else
void signal_handler(int signum) {
if (signum == SIGINT) {
stop = 1;
}
}
#endif
static void show_server_usage(const char *prgname) {
printf("Usage: %s [OPTIONS]\n\n", prgname);
printf("\
-p <port> (Optional; Default: %s)\n\n",
default_port);
return;
}
static void show_client_usage(const char *prgname) {
printf("Usage: %s [OPTIONS]\n\n", prgname);
printf("\
-a <host>\n\
-p <port> (Optional; Default: %s)\n\n",
default_port);
return;
}
void parse_server_opts(const int argc, char *argv[], struct socket_info_t *socket_info) {
socket_info->port = default_port;
int opt;
while ((opt = getopt(argc, argv, "p:h")) != -1) {
switch (opt) {
case 'p':
socket_info->port = optarg;
break;
case 'h':
default:
show_server_usage(argv[0]);
exit(0);
}
}
return;
}
void parse_client_opts(const int argc, char *argv[], struct socket_info_t *socket_info) {
socket_info->port = default_port;
int opt;
while ((opt = getopt(argc, argv, "a:p:h")) != -1) {
switch (opt) {
case 'p':
socket_info->port = optarg;
break;
case 'a':
socket_info->host = optarg;
break;
case 'h':
default:
show_client_usage(argv[0]);
exit(EXIT_SUCCESS);
}
}
if (!socket_info->host) {
fputs("-a <host> is required\n", stderr);
exit(EXIT_FAILURE);
}
return;
}
void get_user_input(char *buffer, size_t size, const char *prompt) {
if (prompt) {
printf("%s", prompt);
fflush(stdout);
}
if (fgets(buffer, size, stdin)) {
// Remove trailing newline if it exists
size_t len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
} else {
// fgets failed — clear buffer
buffer[0] = '\0';
}
}