views:

25

answers:

1

For example,in Windows,if I want to make the error message of gethostbyname meaningful,I would need to manually map the error code to message, as follows,

#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")

int
main(void)
{
 struct hostent *host;
 WSAData wsaData;
 int errcode;

 if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
  perror("WSAStartup failed");
  exit(-1);
 }

 host = gethostbyname("www.google.com");

 if (host != NULL) {
  printf("the offical name of the host is: %s\n", host->h_name);
 } else {
  errcode = WSAGetLastError();
  printf("the error code is %d\n", errcode);
  if (errcode == WSAENETDOWN) 
   perror("network down");
  else if (errcode == WSANOTINITIALISED)
   perror("call WSAStartup before");
  else if ...
  perror("gethostbyname failed");
  return -1;
 }

 return 0;
}

Is there easy way to do this?

thanks.

A: 

I think you codes is in the easy way already, check the error code and return the error message. If you just want to make your codes more elegant, you could use an array of custom struct like below.

struct ErrorInfo
{
  int Code;
  const char* Message;
};

ErrorInfo* errorMap = 
{
  { WSAENETDOWN,       "network down" },
  { WSANOTINITIALISED, "call WSAStartup before" },
};

const char* GetErrorMessage(int errorCode)
{
  for(int i=0; i<sizeof(errorMap)/sizeof(ErrorInfo)); i++)
  {
    if(errorMap[i].Code == errorCode)
      return errorMap[i].Message;
  }
  return "";
}
Wen Q.