1、创建一个对话框应用程序,加载windows socket的动态连接库,方法为在对话框的InitDialog函数中增加如下代码:
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;
}
2、在对话框上增加两个编辑框资源,并为其增加成员变量,名称分别为m_sHostName;m_sIPAddress,类型为CString。
3、添加两个私有函数,分别用来获取主机名和IP,函数如下
int CTestWinSockDlg::GetLocalHostName(CString& sHostName)
{
char szHostName[256];
int nRetCode;
nRetCode = gethostname(szHostName,sizeof(szHostName))//调用API来获得主机名;
if(nRetCode != 0)
{
return WSAGetLastError();
}
sHostName = szHostName;
return 0;
}
int CTestWinSockDlg::GetIPAddress(const CString& sHostName,CString& sIPAddress)
{
struct hostent FAR* lpHostEnt = gethostbyname(sHostName);
if(lpHostEnt == NULL)
{
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())
{
return 0;
}
}
return 0;
}
4、在InitDialog函数中加入如下代码,主机名和IP就会显示在对话框的编辑框中;
int nRetCode;
nRetCode = GetLocalHostName(m_sHostName);
nRetCode = GetIPAddress(m_sHostName,m_sIPAddress);
UpdateData(FALSE);