Permalink
Browse files

Basic message response

  • Loading branch information...
1 parent a36fd84 commit 0dad190f8ea25db9fc3506d5c099346484433d41 @txus committed Oct 1, 2011
Showing with 63 additions and 18 deletions.
  1. +2 −1 Makefile
  2. +8 −1 src/micetrap.c
  3. +30 −15 src/server.c
  4. +2 −1 src/server.h
  5. +15 −0 src/utils.c
  6. +6 −0 src/utils.h
View
@@ -2,8 +2,9 @@ CFLAGS=-Wall
all: src/micetrap
-src/micetrap: src/server.o
+src/micetrap: src/utils.o src/server.o
clean:
rm -f src/micetrap
rm -f src/server.o
+ rm -f src/utils.o
View
@@ -1,9 +1,16 @@
#include <stdio.h>
+#include <stdlib.h>
+#include "utils.h"
#include "server.h"
int main(int argc, char *argv[])
{
+ if (argc < 2) die("USAGE: micetrap <port>");
+
+ int port = atoi(argv[1]);
+
printf("Starting server...\n");
- Server_start(9999);
+
+ Server_start(port);
return 0;
}
View
@@ -1,32 +1,44 @@
#include <stdio.h>
#include <stdlib.h>
-#include <errno.h>
-
#include <string.h>
#include <unistd.h>
+#include <signal.h>
+
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
+
+#include "utils.h"
#include "server.h"
-void die(const char *message)
+char *get_response()
{
- if (errno) {
- perror(message);
- } else {
- printf("ERROR: %s\n", message);
- }
+ char *response;
+ response = "Hello people!";
+ return response;
+}
- exit(1);
+/* TODO: Clean up file descriptors when exiting. */
+void goodbye()
+{
+ printf("Goodbye!");
}
void Server_start(int port)
{
+ // Trap SIGINT and call goodbye()
+ signal(SIGINT, goodbye);
+
// Declare file descriptors
int listen_fd, accept_fd;
+ int received = 0;
+
+ char *response;
+ int response_length = 0;
+
// Declare server and client addresses
struct sockaddr_in server, client;
@@ -64,15 +76,18 @@ void Server_start(int port)
printf("Incoming connection from %s\n", inet_ntoa(client.sin_addr));
- char buf[255];
- int n;
+ // Receive the probe
+ char *buf;
bzero(buf, 256);
- n = recv(accept_fd, buf, 255, 0);
- printf("Message received: %s", buf);
+ received = recv(accept_fd, buf, 255, 0);
+ if (received == 1) {
+ response = strdup(get_response());
+ response_length = strlen(response);
- send(accept_fd, "Welcome to my server.\n", 22, 0);
+ send(accept_fd, response, response_length, 0);
+ }
- // Close file descriptor
+ // Close the connection
close(accept_fd);
}
}
View
@@ -1,7 +1,8 @@
#ifndef __server_h__
#define __server_h__
-void die(const char *message);
+char *get_response();
+void goodbye();
void Server_start(int port);
#endif
View
@@ -0,0 +1,15 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include "utils.h"
+
+void die(const char *message)
+{
+ if (errno) {
+ perror(message);
+ } else {
+ printf("ERROR: %s\n", message);
+ }
+
+ exit(1);
+}
View
@@ -0,0 +1,6 @@
+#ifndef __utils_h__
+#define __utils_h__
+
+void die(const char *message);
+
+#endif

0 comments on commit 0dad190

Please sign in to comment.