Skip to content

Instantly share code, notes, and snippets.

@Zxce3
Created January 14, 2023 20:26
Show Gist options
  • Save Zxce3/9f8e7ed5c3b7691bc81d83ac815d4977 to your computer and use it in GitHub Desktop.
Save Zxce3/9f8e7ed5c3b7691bc81d83ac815d4977 to your computer and use it in GitHub Desktop.
wtf is this?
// create a mail server without include any library
// compile: gcc -o wtf wtf.c
// run: ./wtf
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#define MAX_MSG 1000
int main(int argc, char *argv[])
{
int sd, newSd, cliLen, n;
struct sockaddr_in cliAddr, servAddr;
char line[MAX_MSG];
// create socket
sd = socket(AF_INET, SOCK_STREAM, 0);
if (sd < 0)
{
perror("cannot open socket ");
exit(1);
}
// bind socket to port
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(atoi(argv[1]));
if (bind(sd, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
{
perror("cannot bind port ");
exit(1);
}
listen(sd, 5);
while (1)
{
printf("%s: waiting for data on port TCP %u ... ", argv[0], atoi(argv[1]));
cliLen = sizeof(cliAddr);
newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen);
if (newSd < 0)
{
perror("cannot accept connection ");
exit(1);
}
// init line
memset(line, 0x0, MAX_MSG);
while (n = recv(newSd, line, MAX_MSG, 0))
{
line[n] = '\0';
printf("%s", line);
fflush(stdout);
}
printf("Server: got from %s:TCP%d : %s", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port), line);
close(newSd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment