Skip to content

Instantly share code, notes, and snippets.

@dakk
Created November 4, 2015 15:41
Show Gist options
  • Save dakk/38e19ebddaae04f868e5 to your computer and use it in GitHub Desktop.
Save dakk/38e19ebddaae04f868e5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define MSG "EchoD (v0.1): What you send me - I send you back!\n"
static int sock, conn;
int handle_reply(char *str)
{
char response[64] = {0};
send(conn, "You said: ", 10, 0);
sprintf(response, str);
send(conn, response, 64, 0);
return 0;
}
int main(int argc, char * argv[])
{
struct sockaddr_in my_addr, client_addr;
int sockopt_on = 1;
int optval;
int sa_in_size = sizeof(struct sockaddr_in);
char reply[2048];
// Get a socket
if((sock = socket(AF_INET, SOCK_STREAM,0)) == -1)
{
perror("socket");
exit(1);
}
// First zero the struct
memset((char *) &my_addr, 0, sa_in_size);
// Now fill in the fields we need
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(atoi(argv[1]));
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
optval = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
// Bind our socket to the port
if(bind(sock,(struct sockaddr *)&my_addr, sa_in_size) == -1)
{
perror("bind");
exit(1);
}
// Start listening for incoming connections
if(listen(sock, 0) == -1)
{
perror("listen");
exit(1);
}
while(1)
{
memset(reply, 0x00, 2048);
// Grab connections
conn = accept(sock, (struct sockaddr *)&client_addr, &sa_in_size);
if(conn == -1)
{
perror("accept");
exit(1);
}
// Send a greeting
send(conn, MSG, strlen(MSG), 0);
while(recv(conn, reply, 2048, 0))
{
handle_reply(reply);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment