Created
April 16, 2020 10:00
-
-
Save deep5050/51dbf16baa412ccd9b23bf03ef40e5f9 to your computer and use it in GitHub Desktop.
establish a server on the first available ip address
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
/* This function establish a server on the first available address | |
args: char* port | |
int backlog value | |
return: update the server_IP : server IP adress on which it has bind | |
*/ | |
int establish_server( char *port, int backlog, char *server_IP) | |
{ | |
int yes = 1; | |
struct addrinfo server_addr, *results, *p; | |
char addr[INET_ADDRSTRLEN]; | |
memset(&server_addr, 0, sizeof(server_addr)); | |
/* | |
struct addrinfo { | |
int ai_flags; | |
int ai_family; | |
int ai_socktype; | |
int ai_protocol; | |
socklen_t ai_addrlen; | |
struct sockaddr *ai_addr; | |
char *ai_canonname; | |
struct addrinfo *ai_next; | |
}; | |
*/ | |
server_addr.ai_family = PF_INET; /* IPv4 */ | |
server_addr.ai_socktype = SOCK_STREAM; /* tcp Stream */ | |
server_addr.ai_flags = AI_PASSIVE; /* fill ip automatically */ | |
/* get all the available address of this machine */ | |
int addr_status; | |
if ((addr_status = getaddrinfo(NULL, port, &server_addr, &results)) != 0) | |
{ | |
printf("[%s] SERVER: ERROR getaddrinfo(): %s\n", timestamp(), gai_strerror(addr_status)); | |
exit(EXIT_FAILURE); | |
} | |
/* bind a socket at the first available address */ | |
for (p = results; p != NULL; p = p->ai_next) | |
{ | |
inet_ntop(p->ai_family, p->ai_addr, addr, sizeof(addr)); | |
printf("[%s] SERVER: Trying to build on: %s", timestamp(), addr); | |
if ((server_fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) | |
{ | |
perror("ERROR socket()"); | |
continue; /* if socket can not be created on this address try another */ | |
} | |
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) | |
{ | |
perror("ERROR setsockopt()"); | |
exit(EXIT_FAILURE); | |
} | |
if (bind(server_fd, p->ai_addr, p->ai_addrlen) == -1) | |
{ | |
perror("ERROR bind()"); | |
continue; | |
} | |
/** | |
* control reaches here if all the above conditions satifie | |
* we have succesfully bound a socket and can exit from this loop | |
*/ | |
break; | |
} | |
freeaddrinfo(results); | |
/** | |
* if we get p== NULL that means we couldn't bind to any of the addresses | |
* should return from the program | |
*/ | |
if (p == NULL) | |
{ | |
return -1; | |
} | |
if (listen(server_fd, backlog) == -1) | |
{ | |
// perror("ERROR listen()"); | |
return -2; | |
} | |
strncpy(server_IP, addr, INET_ADDRSTRLEN); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment