Using switch-case instead of if statements.

This commit is contained in:
Nicolás A. Ortega 2017-07-26 15:36:45 -05:00
parent 07e364f46e
commit d0a673d767
No known key found for this signature in database
GPG Key ID: 3D786FB3123FF1DD

View File

@ -35,18 +35,27 @@ int NeoComm_bind(const unsigned short port) {
sockfd = socket(AF_INET, SOCK_STREAM, 0); sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) if(sockfd < 0)
{ {
if(errno == EACCES) /*
NeoComm_error("Insufficient privileges"); * This declaration is here because if you put it at `default:' then
else if(errno == ENOBUFS) * it complains about the line being a declaration and not a
NeoComm_error("Insufficient resources available"); * statement.
else if(errno == ENOMEM) */
NeoComm_error("Insufficient memory to open socket");
else
{
char error_msg[128]; char error_msg[128];
switch(errno) {
case EACCES:
NeoComm_error("Insufficient privileges");
break;
case ENOBUFS:
NeoComm_error("Insufficient resources available");
break;
case ENOMEM:
NeoComm_error("Insufficient memory to open socket");
break;
default:
snprintf(error_msg, 128, snprintf(error_msg, 128,
"Failed to initiate socket with errno `%d'", errno); "Failed to initiate socket with errno `%d'", errno);
NeoComm_error(error_msg); NeoComm_error(error_msg);
break;
} }
return 0; return 0;
} }
@ -56,30 +65,38 @@ int NeoComm_bind(const unsigned short port) {
serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_addr.s_addr = INADDR_ANY;
if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
{ {
if(errno == EADDRINUSE) char error_msg[128]; // same as before
switch(errno) {
case EADDRINUSE:
NeoComm_error("Address in use"); NeoComm_error("Address in use");
else if(errno == EADDRNOTAVAIL) break;
case EADDRNOTAVAIL:
NeoComm_error("Address unavailable on system"); NeoComm_error("Address unavailable on system");
else if(errno == EAFNOSUPPORT) break;
case EAFNOSUPPORT:
NeoComm_error("Unsupported address family for socket"); NeoComm_error("Unsupported address family for socket");
else if(errno == EALREADY) break;
case EALREADY:
NeoComm_error("Assignment request already exists for socket"); NeoComm_error("Assignment request already exists for socket");
else if(errno == EINVAL) break;
case EINVAL:
NeoComm_error("Socket already bound"); NeoComm_error("Socket already bound");
else if(errno == ENOBUFS) break;
case ENOBUFS:
NeoComm_error("Insufficient resources"); NeoComm_error("Insufficient resources");
else if(errno == EACCES) break;
NeoComm_error("Insufficient priviliges"); case EACCES:
else NeoComm_error("Insufficient privileges");
{ break;
char error_msg[128]; default:
snprintf(error_msg, 128, snprintf(error_msg, 128,
"Failed to bind to socket with errno `%d'", errno); "Failed to bind to socket with errno `%d'", errno);
NeoComm_error(error_msg); NeoComm_error(error_msg);
break;
} }
return 0; return 0;
} }
listen(sockfd, 5); listen(sockfd, 5);
return 1; return 1;
} }