views:

68

answers:

2

Hello,

Visual Studio C++ 2008

I am using this code. However, gethostbyname always returns an error. Everything looks ok to me, so I don't understand why I am getting this error.

This is the code I am using up to getting the gethostbyname.

Any think obvious that I might be doing wrong?

int32_t sockfd;
/* struct definition */
struct sockaddr_in conn_addr;

/* gethostbyname for the function and struct definition */
struct hostent *server_hostname;

/* set address to connect to the local loopback */
char buffer[BUF_SIZE] = "127.0.0.1";
char data[BUF_SIZE] = {0};

/* getting hostname for the ip address stored in the buffer */
if((server_hostname = gethostbyname(buffer)) == NULL)
{
        /* gethostbyname uses a special h_errno for error number */
        fprintf(stderr, "gethostbyname [ %s ] [ %s ] [ %d ]\n", strerror(h_errno), __FUNCTION__, __LINE__);
        return CS_FAILURE;
}

The error that gets returned is 'Unknown Error' which doesn't help too much.

Many thanks for any suggestions,

+2  A: 

You should be able to get the 'real' error using WSAGetLastError.

BTW, I assume you did call WSAStartup to initialise the socket subsystem before calling gethostbyname?

Timo Geusch
+3  A: 

You need to add WSAStartup;

WSADATA wsaData;
struct hostent *remoteHost;
char *host_name = "127.0.0.1";

WSAStartup(MAKEWORD(2, 2), &wsaData);

remoteHost = gethostbyname(host_name);
Fredrik Ullner