Created
August 15, 2017 20:06
-
-
Save chaitanyagupta/3ade02deb6025caf335f81edd8ffd729 to your computer and use it in GitHub Desktop.
Bind and listen on a Berkley socket
This file contains hidden or 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/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