-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer1.c
More file actions
98 lines (80 loc) · 2.69 KB
/
Server1.c
File metadata and controls
98 lines (80 loc) · 2.69 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#define close(fd) closesocket(fd)
// Automatic Winsock initialization and cleanup
static void init_winsock() __attribute__((constructor));
static void cleanup_winsock() __attribute__((destructor));
static void init_winsock() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed\n");
exit(EXIT_FAILURE);
}
}
static void cleanup_winsock() {
WSACleanup();
}
#define PORT 8080 // Port number for the server
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
// 1. Create socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// 2. Bind socket to an IP/Port
address.sin_family = AF_INET; // IPv4
address.sin_addr.s_addr = INADDR_ANY; // Any IP address
address.sin_port = htons(PORT); // Host to Network Short
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Binding failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 3. Listen for incoming connections
if (listen(server_fd, 1) < 0) {
perror("Listening failed");
close(server_fd);
exit(EXIT_FAILURE);
}
printf("Server is listening on port %d...\n", PORT);
// 4. Accept a connection
new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
if (new_socket == -1) {
perror("Accepting connection failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 5. Receive data from the client
recv(new_socket, buffer, sizeof(buffer), 0);
printf("Received from client: %s\n", buffer);
// 6. Reverse the string using bubble sort logic
int len = strlen(buffer);
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
char temp = buffer[j];
buffer[j] = buffer[j + 1];
buffer[j + 1] = temp;
}
}
// Convert the reversed string to uppercase
for (int i = 0; buffer[i] != '\0'; i++) {
buffer[i] = toupper(buffer[i]);
}
// 7. Send the response to the client
send(new_socket, buffer, strlen(buffer), 0);
printf("Modified message sent to client: %s\n", buffer);
// 8. Close the sockets
close(new_socket);
close(server_fd);
return 0;
}