C++:gethostname,gethostbyname获取IP地址和计算机名
2017-03-24 09:57
441 查看
使用gethostname()和gethostbyname()获取IP地址和计算机名,记录一下,省得老忘。
[cpp] view plain copy
int CNetTestDlg::GetLocalHostName( CString& sHostName ) // 获取机器名
{
char szHostName[256];
int nRetCode;
nRetCode = gethostname(szHostName, sizeof(szHostName));
if (nRetCode != 0)
{
memcpy(szHostName, ("Not Available"), sizeof("Not Available"));
return WSAGetLastError();
}
sHostName = szHostName;
return 0;
}
[cpp] view plain copy
int CNetTestDlg::GetIPAddress(const CString& sHostName, CString& sIPAddress) // 获取IP地址
{
struct hostent *lpHostEnt = gethostbyname(sHostName);
if (lpHostEnt == NULL)
{
sIPAddress = "";
return WSAGetLastError();
}
LPSTR lpAddr = lpHostEnt->h_addr;
if (lpAddr)
{
struct in_addr inAddr;
memmove(&inAddr, lpAddr, 4); // 将地址进行转换成常规形式
sIPAddress = inet_ntoa(inAddr);
if (sIPAddress.IsEmpty())
{
sIPAddress = "Not available";
}
}
return 0;
}
[cpp] view plain copy
int CNetTestDlg::GetLocalHostName( CString& sHostName ) // 获取机器名
{
char szHostName[256];
int nRetCode;
nRetCode = gethostname(szHostName, sizeof(szHostName));
if (nRetCode != 0)
{
memcpy(szHostName, ("Not Available"), sizeof("Not Available"));
return WSAGetLastError();
}
sHostName = szHostName;
return 0;
}
[cpp] view plain copy
int CNetTestDlg::GetIPAddress(const CString& sHostName, CString& sIPAddress) // 获取IP地址
{
struct hostent *lpHostEnt = gethostbyname(sHostName);
if (lpHostEnt == NULL)
{
sIPAddress = "";
return WSAGetLastError();
}
LPSTR lpAddr = lpHostEnt->h_addr;
if (lpAddr)
{
struct in_addr inAddr;
memmove(&inAddr, lpAddr, 4); // 将地址进行转换成常规形式
sIPAddress = inet_ntoa(inAddr);
if (sIPAddress.IsEmpty())
{
sIPAddress = "Not available";
}
}
return 0;
}
相关文章推荐
- gethostname()和gethostbyname()获取IP地址和计算机名
- 使用gethostname()和gethostbyname()获取IP地址和计算机名
- 使用gethostnamebyname获取百度官方域名及ip地址
- gethostname获取主机IP地址
- 使用gethostname()函数和gethostbyname()函数获取主机相关信息
- 使用gethostname()函数和gethostbyname()函数获取主机相关信息
- UNIX环境编程------Unix编程实例------Gethostbyname和gethostname结合使用打印出主机IP地址
- 使用gethostname()函数和gethostbyname()函数获取主机相关信息
- 使用gethostname()函数和gethostbyname()函数获取主机相关信息
- 获取本地IP gethostname和gethostbyname
- 获取IP地址getsockname gethostname
- GetComputerName正确获取中英文计算机名
- getaddrinfo, getnameinfo(替代gethostbyname, gethostbyaddr), gethostname
- C++ 中通过GetAdaptersInfo获取网卡配置和Ip地址信息
- C++ 中通过GetAdaptersInfo获取网卡配置和Ip地址信息
- C++ 中通过GetAdaptersInfo获取网卡配置和Ip地址信息
- C++ 中通过GetAdaptersInfo获取网卡配置和Ip地址信息
- c#.net使用WinAPI: GetComputerName - 获取计算机名称
- C++ 中通过GetAdaptersInfo获取网卡配置和Ip地址信息
- 在socket编程中,如何获取连接另一端(客户端)的ip地址,使用accept或者getpeername