Skip to content

Instantly share code, notes, and snippets.

@pavi2410
Last active August 10, 2021 15:53
Show Gist options
  • Save pavi2410/4b6201bd19e5f5cc0349492af0b8ee28 to your computer and use it in GitHub Desktop.
Save pavi2410/4b6201bd19e5f5cc0349492af0b8ee28 to your computer and use it in GitHub Desktop.
TCP echo server-client

TCP Echo Server-Client in C

  • Works on Linux
  • Only single client can connect at a time
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
int main() {
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(3000);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int sockfd;
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
printf("couldn't create socket\n");
return 1;
}
printf("socket created\n");
if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
printf("couldn't connect\n");
return 1;
}
printf("connected to the server\n");
char msg[100], server_msg[100];
while (1) {
printf("write message : ");
scanf("%[^\n]%*c", msg);
send(sockfd, msg, sizeof(msg), 0);
memset(server_msg, 0, sizeof(server_msg));
recv(sockfd, server_msg, sizeof(server_msg) , 0);
printf("Server reply : %s\n", server_msg);
if (strcmp(server_msg, "bye") == 0) {
printf("exiting...\n");
break;
}
}
close(sockfd);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(3000);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int sockfd;
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
printf("couldn't create socket\n");
return 1;
}
printf("socket created\n");
if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
printf("couldn't bind socket\n");
return 1;
}
printf("bind at port 3000\n");
if (listen(sockfd, 5) < 0) {
printf("couldn't listen to socket\n");
return 1;
}
printf("listening connection: 5\n");
struct sockaddr_in client_addr;
int client_addr_size = sizeof(client_addr);
while (1) {
int client_sockfd;
if ((client_sockfd = accept(sockfd, (struct sockaddr *) &client_addr, &client_addr_size)) < 0) {
printf("couldn't accept connection\n");
return 1;
}
printf("accepted connection from %s\n", inet_ntoa(client_addr.sin_addr));
char msg[100];
while(1) {
recv(client_sockfd, msg, sizeof(msg), 0);
printf("msg recv = %s\n", msg);
send(client_sockfd, msg, sizeof(msg), 0);
if (strcmp(msg, "bye") == 0) {
printf("exiting...\n");
break;
}
}
close(client_sockfd);
}
close(sockfd);
return 0;
}
@pavi2410
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment