Created
March 2, 2018 18:58
-
-
Save Gydo194/ad71500950b83921189dce04d2f8991b to your computer and use it in GitHub Desktop.
C++ echo server (single client)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> //strlen | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <unistd.h> //close | |
#include <arpa/inet.h> //close | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#define PORT 8888 | |
#define INPUT_BUFFER_SIZE 3 | |
char inputBuffer[INPUT_BUFFER_SIZE]; | |
int listen_fd, comm_fd; | |
struct sockaddr_in servaddr; | |
int main() { | |
listen_fd = socket(AF_INET, SOCK_STREAM, 0); | |
bzero(&servaddr, sizeof (servaddr)); | |
servaddr.sin_family = AF_INET; | |
servaddr.sin_addr.s_addr = htons(INADDR_ANY); | |
servaddr.sin_port = htons(PORT); | |
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof (servaddr)); | |
listen(listen_fd, 10); | |
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL); | |
while (1) { | |
bzero(inputBuffer, INPUT_BUFFER_SIZE); | |
read(comm_fd, inputBuffer, INPUT_BUFFER_SIZE); | |
printf("Echoing back - %s", inputBuffer); | |
write(comm_fd, inputBuffer, strlen(inputBuffer) + 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment