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