Skip to content

Instantly share code, notes, and snippets.

@SwimmingTiger
Last active October 5, 2017 08:52
Show Gist options
  • Save SwimmingTiger/c89070eba7a54175b38f1ef707b7a058 to your computer and use it in GitHub Desktop.
Save SwimmingTiger/c89070eba7a54175b38f1ef707b7a058 to your computer and use it in GitHub Desktop.
simply-tcp-server.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
int main(int argc, char** argv)
{
if(argc != 2)
{
printf("Usage:\n%s <port>\n", argv[0]);
return 0;
}
struct sockaddr_in myAddr, clientAddr;
int socketFd, clientFd;
unsigned int clientAddrLen = sizeof(clientAddr);
int receivedLength;
char buffer[BUFFER_SIZE];
memset(&clientAddr, 0, sizeof(clientAddr));
memset(&myAddr, 0, sizeof(myAddr));
myAddr.sin_family = AF_INET;
myAddr.sin_port = htons(atoi(argv[1]));
// Listen 127.0.0.1
myAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
// or Listen 0.0.0.0
//myAddr.sin_addr.s_addr = htonl(INADDR_ANY);
socketFd = socket(AF_INET, SOCK_STREAM, 0);
bind(socketFd, (struct sockaddr*)&myAddr, sizeof(myAddr));
listen(socketFd, 5);
clientFd = accept(socketFd, (struct sockaddr *)&clientAddr, &clientAddrLen);
receivedLength = recv(clientFd, buffer, BUFFER_SIZE, 0);
buffer[receivedLength] = '\0';
printf("Received a message from %s:%u:\n%s\n"
, inet_ntoa(clientAddr.sin_addr)
, ntohs(clientAddr.sin_port),buffer);
send(clientFd, buffer, receivedLength, 0);
close(clientFd);
close(socketFd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment