Commit 99060b9f authored by Joanne Hugé's avatar Joanne Hugé

Add simple server application

parent 4a16b459
*.o
*.d
simple-server/build/main
PROG = main
SRCDIR = ../src
SRCS = main.c
OBJS = $(SRCS:%.c=%.o)
DEPS = $(SRCS:%.c=%.d)
CFLAGS = -O1 -g -Wall -Werror -Wextra
CFLAGS += -MD -MP
CFLAGS += -I $(SRCDIR)
CFLAGS += -std=gnu99
vpath %.c $(SRCDIR)
$(PROG): $(OBJS)
$(CC) $(LDFLAGS) $^ -o $@
-include $(DEPS)
run: $(PROG)
./$^
clean:
$(RM) $(PROG) $(OBJS) $(DEPS)
.PHONY: clean, run
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define SERVER_PORT "50000"
#define BUFFER_SIZE 1024
static void *get_in_addr(struct sockaddr *sa) {
if(sa->sa_family == AF_INET)
return &(((struct sockaddr_in*) sa)->sin_addr);
return &(((struct sockaddr_in6*) sa)->sin6_addr);
}
int main() {
int status;
int sockfd;
struct addrinfo hints, *servinfo, *servinfo_it;
int bytes_received = 0;
struct sockaddr_storage client_addr;
socklen_t addr_len;
char client_addr_str[INET6_ADDRSTRLEN];
char buf[BUFFER_SIZE];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE;
status = getaddrinfo(NULL, SERVER_PORT, &hints, &servinfo);
if( status != 0 ) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
printf("getaddrinfo: %s\n", gai_strerror(status));
return 1;
}
for(servinfo_it = servinfo; servinfo_it; servinfo_it = servinfo_it->ai_next) {
sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
if( sockfd == -1 ) {
printf("Socket error, continuing...\n");
continue;
}
if( bind(sockfd, servinfo_it->ai_addr, servinfo_it->ai_addrlen) == -1 ) {
close(sockfd);
printf("Bind error, continuing...\n");
continue;
}
break;
}
freeaddrinfo(servinfo);
addr_len = sizeof client_addr;
printf("waiting to recvfrom...\n");
while(1) {
if( (bytes_received = recvfrom(sockfd, buf, BUFFER_SIZE-1, 0,
(struct sockaddr *)&client_addr, &addr_len)) == -1) {
printf("recvfrom error\n");
return 2;
}
inet_ntop(client_addr.ss_family,
get_in_addr((struct sockaddr *)&client_addr),
client_addr_str, sizeof(client_addr_str));
buf[bytes_received] = '\0';
printf("got packet from %s: %s (%d long)\n", client_addr_str, buf, bytes_received);
}
close(sockfd);
return 0;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment