0% found this document useful (0 votes)
5 views3 pages

Code C

This document is a C program that implements a simple TCP server. It creates a socket, binds it to a specified port, listens for incoming connections, and accepts two clients. The server then enters a communication loop where it reads messages from the first client and allows the user to respond.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Code C

This document is a C program that implements a simple TCP server. It creates a socket, binds it to a specified port, listens for incoming connections, and accepts two clients. The server then enters a communication loop where it reads messages from the first client and allows the user to respond.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#include <stdio.

h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <arpa/inet.h>

#define PORT 8080

int main() {

int server_fd, new_socket;

struct sockaddr_in address;

int addrlen = sizeof(address);

// Création du socket

if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {

perror("socket failed");

exit(EXIT_FAILURE);

// Configuration de l'adresse du serveur

address.sin_family = AF_INET;

address.sin_addr.s_addr = INADDR_ANY;

address.sin_port = htons(PORT);

// Attachement du socket à l'adresse et au port spécifiés


if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {

perror("bind failed");

exit(EXIT_FAILURE);

// Mise en écoute du socket

if (listen(server_fd, 2) < 0) {

perror("listen");

exit(EXIT_FAILURE);

// Acceptation des connexions entrantes

if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {

perror("accept");

exit(EXIT_FAILURE);

// Attente d'un deuxième client

if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {

perror("accept");

exit(EXIT_FAILURE);

// Boucle de communication

while (1) {
char buffer[1024] = {0};

int valread;

// Lecture du message du premier client

valread = read(new_socket , buffer, 1024);

printf("L'autre client dit : %s\n", buffer);

// Saisie de la réponse

printf("Saisissez la réponse : ");

fgets(buffer, 1024, stdin);

send(new_socket , buffer , strlen(buffer) , 0);

return 0;

You might also like