如何得到本机的IP地址
做毕业设计,想要用本机IP地址的后3位作为在该机上运行客户端程序的编号,在
VC6.0下如何得到该机的IP地址呢?请赐教。
问题点数:80、回复次数:10Top
1 楼zfive5(醉马不肖)回复于 2004-05-04 14:39:59 得分 20
gethostname()Top
2 楼zfive5(醉马不肖)回复于 2004-05-04 14:42:17 得分 20
struct hostent* FAR gethostbyname(
const char* name
);
Top
3 楼zfive5(醉马不肖)回复于 2004-05-04 14:51:46 得分 20
hostent* hn;
hn = gethostbyname(m_cHostname);
CString strIPAddr;
strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);
Top
4 楼qyshooter(青阳)回复于 2004-05-04 19:58:34 得分 0
可是每次得到的都是127.0.0.1,而且我只要IP的最后一个"."号后的三个数字,怎么办呢?Top
5 楼zhjie374(zhjie374)回复于 2004-05-04 21:35:38 得分 10
hostent* hn;
hn = gethostbyname(m_cHostname);
CString strIPAddr;
strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);
可以得到本机IP
需要最后3个数字,可以将IP的点分格式转换成字符串.然后对字符串去操作!Top
6 楼dTianx(铁锈)回复于 2004-05-04 21:38:05 得分 0
gethostname
gethostbynameTop
7 楼yhqs540(Reich)回复于 2004-05-05 07:39:37 得分 10
gethostbyname
或者给自己发送arp包。Top
8 楼code8238(二进制动物)回复于 2004-05-05 08:15:58 得分 0
////////////////
// 初始化 Windows sockets API. 要求版本为 version 1.1
//
WORD wVersionRequested = MAKEWORD(1, 1);
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData))
{
AfxMessageBox("初始化WINSOCKAPI失败");
}
//////////////////
// 获得主机名.
//
if (gethostname(HostName, sizeof(HostName))!=0)
{
AfxMessageBox("取得主机名失败");
}
////////////////
// 根据主机名获取主机信息.
//
pHostent=gethostbyname(HostName);
if (pHostent==NULL)
{
AfxMessageBox("取得主机信息失败");
}
//////////////////
// 解析返回的hostent信息.
//
sockaddr_in sa;
for (int nAdapter=0; pHostent->h_addr_list[nAdapter]; nAdapter++)
{
memcpy(&sa.sin_addr.s_addr, pHostent->h_addr_list[nAdapter],pHostent->h_length);
//把IP列表中的每个IP存放在sockaddr_in结构变量sa中
memcpy(HostIPList[nAdapter],inet_ntoa(sa.sin_addr),16);
//把sa中的IP转换成字符串存放在HostIPList中
}//取得每块网卡的IP地址并存放在HostIPList中
//////////////////
// 终止 Windows sockets API
//
WSACleanup();
//////////////////Top
9 楼sharkhuang(走吧走吧!人总会慢慢长大~)回复于 2004-05-05 10:33:33 得分 0
gethostname()
gethostbyname()Top
10 楼zhucde(【風間苍月】★<==>★【虚拟闲人】)回复于 2004-06-16 23:59:01 得分 0
int GetIpAddress(const CString &sHostName, CStringArray &sIpAddress)
{
struct hostent FAR * lpHostEnt=gethostbyname(sHostName);
sIpAddress.RemoveAll();
if(lpHostEnt==NULL)
{
//产生错误
return GetLastError();
}
//获取IP
int i=0;
LPSTR lpAddr=lpHostEnt->h_addr_list[i];
CString temp;
while(lpAddr)
{
i++;
struct in_addr inAddr;
memmove(&inAddr,lpAddr,4);
//转换为标准格式
temp=inet_ntoa(inAddr);
if(temp.IsEmpty())
{
break;
}
sIpAddress.Add(temp);
lpAddr=lpHostEnt->h_addr_list[i];
}
return 0;
}
调用:
if(AfxSocketInit(NULL)==FALSE)//初始化socket
{
AfxMessageBox("Socket Error");
}
CStringArray ip;
CString m_sHostName;
char hosttemp[256];
gethostname(hosttemp,256);
m_sHostName=hosttemp;//如果这里,m_sHostName="www.163.com",将得到网易的IP
GetIpAddress(dlg.m_sHostName,ip);//获得本地IP
CString temp;
int i=0;
while(i<ip.GetSize())
{
temp+=ip[i];
temp+=";\n";
i++;
}
MessageBox(dlg.m_sHostName+"的IP是:\n"+temp);
}
Top




