您的位置:首页 > 其它

VC中获取主机名和IP地址的方法

2008-05-27 10:50 573 查看
function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: