Last active
August 29, 2015 14:16
-
-
Save jeremyheiler/3e7c6fee61f42c4a3ca9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <unistd.h> | |
int | |
main(int argc, char *argv[]) | |
{ | |
int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (sock == -1) { | |
perror("Socket"); | |
return -1; | |
} | |
printf("Socket FD: %d\n", sock); | |
int one = 1; | |
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int)) == -1) { | |
perror("Sockopt"); | |
return -1; | |
} | |
struct sockaddr_in addr; | |
memset(addr.sin_zero, '\0', sizeof addr.sin_zero); | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(2323); | |
addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
int b = bind(sock, (struct sockaddr *) &addr, sizeof addr); | |
if (b == -1) { | |
perror("Bind"); | |
return -1; | |
} | |
int l = listen(sock, 10); | |
if (l == -1) { | |
perror("Listen"); | |
return -1; | |
} | |
int a; | |
struct sockaddr accept_addr; | |
socklen_t addr_len; | |
ssize_t read; | |
char buf[128]; | |
/* | |
for (;;) { | |
*/ | |
a = accept(sock, &accept_addr, &addr_len); | |
if (a == -1) { | |
perror("Accept"); | |
return -1; | |
} | |
printf("Got it\n"); | |
read = recv(a, (void *) &buf, 127, 0); | |
printf("read %zd\n", read); | |
if (read == -1) { | |
perror("Recv"); | |
return -1; | |
} | |
if (read == 0) { | |
perror("Recv"); | |
printf("peer closed conn\n"); | |
return -1; | |
} | |
buf[(int) read] = '\0'; | |
printf("%s", buf); | |
/* | |
} | |
*/ | |
int c = close(sock); | |
if (c == -1) { | |
perror("Close"); | |
return -1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment