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"); char error_msg[128];
else switch(errno) {
{ case EACCES:
char error_msg[128]; NeoComm_error("Insufficient privileges");
snprintf(error_msg, 128, break;
"Failed to initiate socket with errno `%d'", errno); case ENOBUFS:
NeoComm_error(error_msg); NeoComm_error("Insufficient resources available");
break;
case ENOMEM:
NeoComm_error("Insufficient memory to open socket");
break;
default:
snprintf(error_msg, 128,
"Failed to initiate socket with errno `%d'", errno);
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
NeoComm_error("Address in use"); switch(errno) {
else if(errno == EADDRNOTAVAIL) case EADDRINUSE:
NeoComm_error("Address unavailable on system"); NeoComm_error("Address in use");
else if(errno == EAFNOSUPPORT) break;
NeoComm_error("Unsupported address family for socket"); case EADDRNOTAVAIL:
else if(errno == EALREADY) NeoComm_error("Address unavailable on system");
NeoComm_error("Assignment request already exists for socket"); break;
else if(errno == EINVAL) case EAFNOSUPPORT:
NeoComm_error("Socket already bound"); NeoComm_error("Unsupported address family for socket");
else if(errno == ENOBUFS) break;
NeoComm_error("Insufficient resources"); case EALREADY:
else if(errno == EACCES) NeoComm_error("Assignment request already exists for socket");
NeoComm_error("Insufficient priviliges"); break;
else case EINVAL:
{ NeoComm_error("Socket already bound");
char error_msg[128]; break;
snprintf(error_msg, 128, case ENOBUFS:
"Failed to bind to socket with errno `%d'", errno); NeoComm_error("Insufficient resources");
NeoComm_error(error_msg); break;
case EACCES:
NeoComm_error("Insufficient privileges");
break;
default:
snprintf(error_msg, 128,
"Failed to bind to socket with errno `%d'", errno);
NeoComm_error(error_msg);
break;
} }
return 0; return 0;
} }
listen(sockfd, 5); listen(sockfd, 5);
return 1; return 1;
} }