获取本机的IP地址

coolali 2003-10-15 10:19:25
在网上查找了一下,发现代码都很烦琐,不知哪位高手知道简单的方法或API
比较轻松获取本机的IP地址。
...全文
77 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Davidzhuhua 2003-10-15
  • 打赏
  • 举报
回复
BOOL Name2Ips(CString& strHostName,CUIntArray &aIp) //resolve a string ip or name to ip
{
aIp.RemoveAll();

LPHOSTENT lpstHost = NULL;
UINT nIp = inet_addr((LPCTSTR)strHostName);//is a IP address
if (nIp == INADDR_NONE)
{
lpstHost = gethostbyname((LPCTSTR)strHostName);//is a Name
if (!lpstHost)
return FALSE;
else
for(int i = 0; lpstHost!= NULL && lpstHost->h_addr_list[i]!= NULL; i++ )
aIp.Add(*(UINT *)lpstHost->h_addr_list[i]);
}
else
aIp.Add(nIp);
return TRUE;
}
UINT String2Ip(LPCTSTR szHost)
{
CUIntArray aIp;
if(Name2Ips(CString(szHost),aIp))
{
return aIp[0];
}
else
return 0;
}
CString Ip2String(UINT nIp)
{
if(!nIp)
return CString((LPCTSTR)NULL); //zero
char buff[16];
sprintf(buff,"%d.%d.%d.%d",nIp%256,nIp/256%256,nIp/256/256%256,nIp/256/256/256);
return CString(buff);
}
crs96321 2003-10-15
  • 打赏
  • 举报
回复
[程序实现]
假设你有了名为My的对话框工程.有一个按钮并有响应的程序:如OnButton1();
BOOL CListCtrl1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
AfxSocketInit(NULL);
//支持Socket.若在向导是没选Support Socket,这就的加.
//还要加#include <afxsock.h>在StdAfx.h中.

.......
// Add "About..." menu item to system menu.

// IDM_ABOUTBOX must be in the system command range.

// TODO: Add extra initialization here

return TRUE; // return TRUE unless you set the focus to a control
}

void CListCtrl1Dlg::OnButton1()
{
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
CString ip;
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD( 2, 0 );

if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
{

if( gethostname ( name, sizeof(name)) == 0)
{
if((hostinfo = gethostbyname(name)) != NULL)
{
ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
}
}

WSACleanup( );
}
AfxMessageBox(name);//name里是本机名
AfxMessageBox(ip); //ip中是本机IP


这段代码应该是很简单详细了!
SeainBlue 2003-10-15
  • 打赏
  • 举报
回复
char *GetLocalIP()
{
struct in_addr localaddr;
struct hostent *hp=NULL;
char hostname[50];
gethostname(hostname,49);//主机名
hp=gethostbyname(hostname);主机信息
memcpy(&localaddr,hp->h_addr,hp->length);//地址
return inet_ntoa(localaddr);//变成char *

}
SeainBlue 2003-10-15
  • 打赏
  • 举报
回复
gethostbyname

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧