Initial commit
This commit is contained in:
38
src/socketHelp.c
Normal file
38
src/socketHelp.c
Normal file
@@ -0,0 +1,38 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
int createSocket(int port, int *server_fd, struct sockaddr_in *address, int *addrlen) {
|
||||
int opt = 1;
|
||||
|
||||
// Create socket fd
|
||||
if ((*server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
|
||||
perror("socket failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
// Attach socket to PORT
|
||||
if (setsockopt(*server_fd, SOL_SOCKET, SO_REUSEADDR |SO_REUSEPORT,
|
||||
&opt, sizeof(opt))) {
|
||||
perror("Set socket opt failure");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
address->sin_family = AF_INET;
|
||||
address->sin_addr.s_addr = INADDR_ANY;
|
||||
address->sin_port = htons (port);
|
||||
|
||||
// Attach to PORT
|
||||
if (bind(*server_fd, (struct sockaddr *)address,
|
||||
sizeof(*address))<0) {
|
||||
perror("Failed to bind");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (listen(*server_fd, 3) < 0) {
|
||||
perror("Failed to listen");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user