Skip to content

Instantly share code, notes, and snippets.

@tonitch
Created December 9, 2021 14:42
Show Gist options
  • Save tonitch/62235ffd9eb070025f1ba9ffe819c067 to your computer and use it in GitHub Desktop.
Save tonitch/62235ffd9eb070025f1ba9ffe819c067 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <iostream>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <cstring>
int main(int argc, char* argv[]){
int sockfd, new_fd;
struct sockaddr_in my_sockaddr, their_sockaddr;
unsigned int sin_size;
char command[1024];
memset(&my_sockaddr, 0, sizeof(my_sockaddr));
my_sockaddr.sin_family = AF_INET;
my_sockaddr.sin_addr.s_addr = INADDR_ANY;
my_sockaddr.sin_port = htons(2142);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
if(bind(sockfd, (struct sockaddr*) &my_sockaddr, sizeof(struct sockaddr)) < 0){
perror("bind");
exit(1);
}
if(listen(sockfd, 5) == -1){
perror("bind");
exit(1);
}
sin_size = sizeof(struct sockaddr_in);
while(true){
new_fd = accept(sockfd, (struct sockaddr*)&their_sockaddr, &sin_size);
std::cout << "The server has received : " << inet_ntoa(their_sockaddr.sin_addr) << std::endl;
recv(new_fd, &command, 1024, 0);
std::cout << inet_ntoa(their_sockaddr.sin_addr) << ": " << command << ": hey"<< std::endl;
if(command == "ping"){
send(new_fd, "pong!", 5, 0);
}
close(new_fd);
/* if(!fork()){ */
/* if(send(new_fd, "Hello, world!\n", 14,0) == -1){ */
/* perror("send"); */
/* close(new_fd); */
/* exit(0); */
/* } */
/* close(new_fd); */
/* while(waitpid(-1, NULL, WNOHANG) > 0); */
/* } */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment