Last active
September 28, 2018 13:53
-
-
Save eugeniomiro/c8baa2d5ad16c660dc20bb831fefa7d9 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 <sys/socket.h> | |
#include <netinet/in.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <string.h> | |
#define MY_SOCK_PATH "/somepath" | |
#define LISTEN_BACKLOG 50 | |
#define handle_error(msg) \ | |
do { perror(msg); exit(EXIT_FAILURE); } while (0) | |
int | |
main(int argc, char *argv[]) | |
{ | |
int sfd, cfd; | |
struct sockaddr_in my_addr, peer_addr; | |
socklen_t peer_addr_size; | |
sfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sfd == -1) | |
handle_error("socket"); | |
memset(&my_addr, 0, sizeof(struct sockaddr_in)); | |
/* Clear structure */ | |
my_addr.sin_family = AF_INET; | |
my_addr.sin_port = htons(23456); | |
my_addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
if (bind(sfd, (struct sockaddr *) &my_addr, | |
sizeof(struct sockaddr_in)) == -1) | |
handle_error("bind"); | |
printf("socket bound, press ENTER"); | |
getchar(); | |
if (listen(sfd, LISTEN_BACKLOG) == -1) | |
handle_error("listen"); | |
printf("socket listening, press ENTER"); | |
getchar(); | |
/* Now we can accept incoming connections one | |
at a time using accept(2) */ | |
peer_addr_size = sizeof(struct sockaddr_in); | |
cfd = accept(sfd, (struct sockaddr *) &peer_addr, | |
&peer_addr_size); | |
if (cfd == -1) | |
handle_error("accept"); | |
/* Code to deal with incoming connection(s)... */ | |
/* When no longer required, the socket pathname, MY_SOCK_PATH | |
should be deleted using unlink(2) or remove(3) */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment