2010-03-07 106 views
0

Visual Studio C++ 2008winsock gethostbyname失败

我正在使用此代码。但是,gethostbyname总是返回一个错误。一切看起来都对我好,所以我不明白为什么我得到这个错误。

这是我用来获取gethostbyname的代码。

任何想法显而易见,我可能会做错?

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; 
} 

返回的错误是'未知错误',这不会帮助太多。

非常感谢您的任何建议,

回答

3

您需要添加WSAStartup;

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

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

remoteHost = gethostbyname(host_name); 
3

你应该能够得到使用WSAGetLastError“真正的”错误。

顺便说一句,我假设您在调用gethostbyname之前调用WSAStartup来初始化套接字子系统?