tcp/quic lab finished
This commit is contained in:
75
network/tcpquiclab/tcp_server.c
Normal file
75
network/tcpquiclab/tcp_server.c
Normal file
@ -0,0 +1,75 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/socket.h>
|
||||
|
||||
#define PORT 8080
|
||||
#define BUFFER_SIZE 1024
|
||||
|
||||
int main() {
|
||||
int server_fd, new_socket;
|
||||
struct sockaddr_in address;
|
||||
int opt = 1;
|
||||
int addrlen = sizeof(address);
|
||||
char buffer[BUFFER_SIZE] = {0};
|
||||
|
||||
// 1. Create socket file descriptor
|
||||
// AF_INET: IPv4, SOCK_STREAM: TCP
|
||||
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
|
||||
perror("socket failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// 2. Attach socket to the port 8080
|
||||
// SO_REUSEADDR allows restarting the server immediately after closing
|
||||
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
|
||||
perror("setsockopt");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
address.sin_family = AF_INET;
|
||||
address.sin_addr.s_addr = INADDR_ANY; // Listen on all interfaces
|
||||
address.sin_port = htons(PORT);
|
||||
|
||||
// Bind
|
||||
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
|
||||
perror("bind failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// 3. Listen for incoming connections
|
||||
if (listen(server_fd, 3) < 0) {
|
||||
perror("listen");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
printf("TCP Server listening on port %d...\n", PORT);
|
||||
|
||||
// 4. Accept connection
|
||||
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
|
||||
perror("accept");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
printf("Client connected.\n");
|
||||
|
||||
// 5. Receive data
|
||||
int valread = read(new_socket, buffer, BUFFER_SIZE);
|
||||
if (valread > 0) {
|
||||
printf("Received %d bytes: %s\n", valread, buffer);
|
||||
|
||||
// 6. Send response (Echo length or simple ack)
|
||||
char response[BUFFER_SIZE];
|
||||
snprintf(response, BUFFER_SIZE, "Server received %d bytes", valread);
|
||||
send(new_socket, response, strlen(response), 0);
|
||||
printf("Response sent to client.\n");
|
||||
}
|
||||
|
||||
// 7. Close socket
|
||||
close(new_socket);
|
||||
close(server_fd);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user