Socket code
This commit is contained in:
parent
6af488012f
commit
d750f55e87
1 changed files with 69 additions and 0 deletions
69
sock.c
Normal file
69
sock.c
Normal file
|
@ -0,0 +1,69 @@
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <netdb.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
// Get TCP protocol entry
|
||||||
|
struct protoent *pent = getprotobyname("tcp");
|
||||||
|
if (!pent) {
|
||||||
|
perror("getprotobyname failed");
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create socket
|
||||||
|
int server_fd = socket(AF_INET, SOCK_STREAM, pent->p_proto);
|
||||||
|
if (server_fd < 0) {
|
||||||
|
perror("socket failed");
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up server address structure
|
||||||
|
struct sockaddr_in server_addr = {
|
||||||
|
.sin_family = AF_INET,
|
||||||
|
.sin_addr.s_addr = htonl(INADDR_ANY), // Bind to any available address
|
||||||
|
.sin_port = htons(8080) // Port 8080
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bind socket
|
||||||
|
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
|
||||||
|
perror("bind failed");
|
||||||
|
close(server_fd);
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listen for incoming connections
|
||||||
|
if (listen(server_fd, 5) < 0) {
|
||||||
|
perror("listen failed");
|
||||||
|
close(server_fd);
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Server listening on port 8080...\n");
|
||||||
|
|
||||||
|
// Accept one client connection
|
||||||
|
struct sockaddr_in client_addr;
|
||||||
|
socklen_t client_len = sizeof(client_addr);
|
||||||
|
int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len);
|
||||||
|
if (client_fd < 0) {
|
||||||
|
perror("accept failed");
|
||||||
|
close(server_fd);
|
||||||
|
return EXIT_FAILURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Client connected!\n");
|
||||||
|
|
||||||
|
// Send a message to the client
|
||||||
|
const char *message = "Hello from server!\n";
|
||||||
|
send(client_fd, message, strlen(message), 0);
|
||||||
|
|
||||||
|
// Cleanup
|
||||||
|
close(client_fd);
|
||||||
|
close(server_fd);
|
||||||
|
|
||||||
|
printf("Exit\n");
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
Loading…
Add table
Reference in a new issue