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。
(完)
原文:http://www.cnblogs.com/fwst/p/3718757.html