Skip to content

Instantly share code, notes, and snippets.

@Josh798
Created November 22, 2020 17:45
Show Gist options
  • Save Josh798/06f4aa1fb9ecfb76f3db21fc6cbcf6eb to your computer and use it in GitHub Desktop.
Save Josh798/06f4aa1fb9ecfb76f3db21fc6cbcf6eb to your computer and use it in GitHub Desktop.
Open a server socket at which TCP connections may be accepted.
#include <stdio.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <arpa/inet.h>
/**
* Returns a socket listening at the specified port. Up to "backlog" connection
* requests will be queued before further requests are refused.
*
* On error, -1 is returned.
*/
int open_server_socket(unsigned short port, int backlog)
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "Could not open socket. %s.\n", strerror(errno));
return -1;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
{
fprintf(stderr, "Could not set SO_REUSEADDR. %s.\n", strerror(errno));
close(sockfd);
return -1;
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr)) <0)
{
fprintf(stderr, "Could not bind to port %hu. %s.\n", port, strerror(errno));
close(sockfd);
return -1;
}
if (listen(sockfd, backlog) < 0)
{
fprintf(stderr, "Could not listen on socket. %s.\n", strerror(errno));
close(sockfd);
return -1;
}
return sockfd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment