首页 > 代码库 > 获取机器名和IP地址
获取机器名和IP地址
VS2010/MFC/对话框
主要用两个函数:gethostname 和 gethostbyname。
int CIPADDRESSDlg::StartUp(void) { WORD wVersionRequested; WSAData wsadata; int err; wVersionRequested = MAKEWORD(2, 0); err = WSAStartup(wVersionRequested, &wsadata); if (err != 0) { return err; } if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion)!= 0) { WSACleanup(); return WSAVERNOTSUPPORTED; } return 0; } int CIPADDRESSDlg::CleanUp(void) { int nRetCode; nRetCode = WSACleanup(); if (nRetCode != 0) { return WSAGetLastError(); } return 0; } int CIPADDRESSDlg::GetLocalHostName(CString & sHostName) { char szHostName[256]; int nRetCode; nRetCode = gethostname(szHostName, sizeof(szHostName)); if (nRetCode != 0) { sHostName = TEXT("Not available"); return WSAGetLastError(); } sHostName = szHostName; return 0; } int CIPADDRESSDlg::GetIPAddress(const CString & sHostName, CString & sIpAddress) { struct hostent FAR * lpHostEnt = gethostbyname(sHostName); if (lpHostEnt == NULL) { sIpAddress = TEXT(""); return WSAGetLastError(); } LPSTR lpAddr = lpHostEnt->h_addr_list[0]; if (lpAddr) { struct in_addr inAddr; memmove(&inAddr, lpAddr, 4); sIpAddress = inet_ntoa(inAddr); if (sIpAddress.IsEmpty()) { sIpAddress = TEXT("Not available"); } } return 0; }
初始化中调用:
// TODO: 在此添加额外的初始化代码 int nRetCode; nRetCode = StartUp(); TRACE1("StartUp RetCode: %d\n", nRetCode); nRetCode = GetLocalHostName(m_sHostName); TRACE1("GetLocalHostName RetCode: %d\n", nRetCode); nRetCode = GetIPAddress(m_sHostName, m_sIpAddress); TRACE1("GetIPAddress RetCode: %d\n", nRetCode); nRetCode = CleanUp(); TRACE1("CleanUp RetCode: %d\n", nRetCode); UpdateData(FALSE);
2. static text控件添加VALUE变量,m_sHostName和m_sIpAddress。
(完)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。