怎样获得本机器的IP地址,该如何处理

怎样获得本机器的IP地址
如上所述。
谢谢大侠

------解决方案--------------------
VC中获取主机名和IP地址的方法
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);


------解决方案--------------------
int nRet = gethostname(szName,100); //获取本机名称
if (nRet != 0)
{
AfxMessageBox( "获取本机IP出错! ");
return FALSE;
}
hostent *phost = gethostbyname(szName); //get host information corresponding to a host name

struct in_addr inAddr;
for (int i=0; i <100; i++)
{
LPSTR lpAddr = phost-> h_addr_list[i];
if (lpAddr != NULL)
{
memmove (&inAddr, lpAddr, 4);
m_strIPAddress = inet_ntoa (inAddr);
if (m_strIPAddress.GetLength() != 0)
{
m_cmbCtrl.AddString(m_strIPAddress);
}
}
else
{
break;
}
}

上面的代码可以获取本机的所有ip
------解决方案--------------------
char hostname[100];
char *m_strLocalIP;

gethostname(hostname,100);
m_strLocalIP=(char *)malloc(100);

struct hostent *host=gethostbyname(hostname);
if(host==NULL) m_strLocalIP= "0.0.0.0 ";
else m_strLocalIP=inet_ntoa(*((in_addr*)host-> h_addr));
printf( "%s\n ",hostname);
printf( "%s\n ",m_strLocalIP);