Skip to content

Instantly share code, notes, and snippets.

@chaitanyagupta
Created August 15, 2017 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaitanyagupta/3ade02deb6025caf335f81edd8ffd729 to your computer and use it in GitHub Desktop.
Save chaitanyagupta/3ade02deb6025caf335f81edd8ffd729 to your computer and use it in GitHub Desktop.
Bind and listen on a Berkley socket
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int bind_and_listen (int port, int backlog) {
int listen_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_fd == -1) {
perror("socket");
return -1;
}
struct sockaddr_in sa;
bzero(&sa, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(listen_fd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
perror("bind");
return -1;
}
if (listen(listen_fd, backlog) == -1) {
perror("listen");
return -1;
}
return listen_fd;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment