-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCreateTCPServerSocket.c
More file actions
33 lines (25 loc) · 1.3 KB
/
CreateTCPServerSocket.c
File metadata and controls
33 lines (25 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <sys/socket.h> /* for socket(), bind(), and connect() */
#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */
#include <string.h> /* for memset() */
#define MAXPENDING 5 /* Maximum outstanding connection requests */
void DieWithError(char *errorMessage); /* Error handling function */
int CreateTCPServerSocket(unsigned short port)
{
int sock; /* socket to create */
struct sockaddr_in echoServAddr; /* Local address */
/* Create socket for incoming connections */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* Construct local address structure */
memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */
echoServAddr.sin_family = AF_INET; /* Internet address family */
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
echoServAddr.sin_port = htons(port); /* Local port */
/* Bind to the local address */
if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
DieWithError("bind() failed");
/* Mark the socket so it will listen for incoming connections */
if (listen(sock, MAXPENDING) < 0)
DieWithError("listen() failed");
return sock;
}