Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[MAX_BUFFER_SIZE] = "Hello, WiFi World!"; // Data to send
// Create a socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
// Initialize server address structure
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// Bind the socket to the server address
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Binding failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_socket, 5) == -1) {
perror("Listening failed");
exit(EXIT_FAILURE);
}
printf("Server listening on port %d...\n", PORT);
// Accept a client connection
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == -1) {
perror("Accepting client connection failed");
exit(EXIT_FAILURE);
}
printf("Client connected\n");
// Send data to the client
send(client_socket, buffer, strlen(buffer), 0);
printf("Data sent to the client: %s\n", buffer);
// Close the sockets
close(client_socket);
close(server_socket);
return 0;
}