获取IP地址问题

org200820082008 2008-10-17 11:04:25
HOSTENT *pHOSTENT;
char name[255];
gethostname(name,sizeof(name));
pHOSTENT=gethostbyname(name);
m_strLocalName=pHOSTENT->h_name;
m_strLocalIP = inet_ntoa(*(struct in_addr*)*pHOSTENT->h_addr_list);

以上代码,为什么在获取计算机名称和IP地址时总是出现异常错误。
...全文
95 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
caitian6 2008-10-24
  • 打赏
  • 举报
回复
楼上说的很清楚啦
Win32Coder 2008-10-24
  • 打赏
  • 举报
回复
gethostname(name,sizeof(name));
怎么没检查返回 值 呢?错误的话用WSAGetLastError()查看一下。
估计楼主没有 初始化吧。 没有调用 WSAStartup().

gethostname()

lasterror:

WSAEFAULT The name parameter is not a valid part of the user address space, or the buffer size specified by the namelen parameter is too small to
hold the complete host name.
WSANOTINITIALISED A successful WSAStartup call must occur before using this function.
WSAENETDOWN The network subsystem has failed.
WSAEINPROGRESS A blocking Winsock call is in progress, or the service provider is still processing a callback function.

Remarks
shuzu8 2008-10-24
  • 打赏
  • 举报
回复
顶。我也想知道怎么获取这东西
糊里糊涂 2008-10-17
  • 打赏
  • 举报
回复
HOSTENT *pHOSTENT = gethostbyname(name);
如果分开写,那么就要先对pHOSTENT初始化
rockq7q7vip 2008-10-17
  • 打赏
  • 举报
回复
LPHOSTENT lphostent;
lphostent=gethostbyname("www.baidu.com");
if(!lphostent)
{
AfxMessageBox("error");
return;
}
else
{

LPSTR szIPAddr;
szIPAddr=inet_ntoa(*(LPIN_ADDR)*(lphostent->h_addr_list));
AfxMessageBox(szIPAddr);
}
jxb_memory 2008-10-17
  • 打赏
  • 举报
回复
// 程序功能:取出本机的所有IP,保存为一个字符串列表

// 作者:someone(阿风)

// windows xp + sp2 , vc6 + sp5编译通过

//

#include

using std::cin;

using std::cout;

using std::cerr;

using std::endl;

#include

using std::list;

#include

using std::string;

#include

#pragma comment( lib, "ws2_32.lib" )

bool GetIpList( list r_iplist )

{

WORD wVersionRequested;

WSADATA wsaData;

int err;

wVersionRequested = MAKEWORD( 2, 2 );

err = WSAStartup( wVersionRequested, &wsaData );

if ( err != 0 )

{

cout < < "WSAStartup failed !" < < endl;

return false;

}

char szhn[256];

int nStatus = gethostname(szhn, sizeof(szhn));

if (nStatus == SOCKET_ERROR )

{

cout < < "gethostname failed, Error code: " < < WSAGetLastError() < < endl;

return false;

}

HOSTENT *host = gethostbyname(szhn);

if (host != NULL)

{

for ( int i=0; ; i++ )

{

r_iplist.push_back( inet_ntoa( *(IN_ADDR*)host-> h_addr_list[i] ) ) ;

if ( host-> h_addr_list[i] + host-> h_length > = host-> h_name )

break;

}

}

WSACleanup();

return true;

}

int main(int argc, char *argv[])

{

list iplist;

std::list ::iterator ip;

if ( !GetIpList( iplist ) )

{

cout < < "Get ip list failed !" < < endl;

return -1;

}

cout < < "IP list :" < < endl;

for ( ip = iplist.begin(); ip != iplist.end(); ip++ )

{

cout < < " " < < *ip < < endl;

}

return 0;

}

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧