我是靠谱客的博主 任性皮皮虾,最近开发中收集的这篇文章主要介绍gethostname()和gethostbyname()获取IP地址和计算机名,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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;
}
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;
}

 

转载于:https://www.cnblogs.com/killer-xc/p/6610188.html

最后

以上就是任性皮皮虾为你收集整理的gethostname()和gethostbyname()获取IP地址和计算机名的全部内容,希望文章能够帮你解决gethostname()和gethostbyname()获取IP地址和计算机名所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部