zoukankan      html  css  js  c++  java
  • MFC-获取本地IP地址并返回cstring

    获取IP地址并返回Cstring

    CString CAddStdDlg::GetLocalIP()
    {
    	WSADATA wsaData;
    	int err = WSAStartup(MAKEWORD(2, 0), &wsaData);
    	if (err != 0)
    	{
    		return _T("");
    	}
    
    	char szHostName[MAX_PATH] = { 0 };
    	int nRetCode;
    	nRetCode = gethostname(szHostName, sizeof(szHostName));
    
    	char* lpLocalIP;
    	PHOSTENT hostinfo;
    
    	if (nRetCode != 0)
    	{
    		WSACleanup();
    		return _T("");
    	}
    
    	hostinfo = gethostbyname(szHostName);
    	lpLocalIP = inet_ntoa(*(struct in_addr*) * hostinfo->h_addr_list);
    
    	CString aa(lpLocalIP);
    
    	WSACleanup();
    
    	return aa;
    }
    

      

    void CMyDlg::GetHostAddress(CString &strIPAddr)
    {
    char    HostName[100];
    gethostname(HostName, sizeof(HostName));// 获得本机主机名.
    
    hostent* hn;
    hn = gethostbyname(HostName);//根据本机主机名得到本机ip
    
    strIPAddr=inet_ntoa(*(struct in_addr *)hn->h_addr_list[0]);//把ip换成字符串形式
    }
    
    //摘自 https://blog.csdn.net/imxiangzi/article/details/38264563
    

      

    代码没有问题,在使用的时候 报错

    warning C4996: 'gethostbyname': Use getaddrinfo() or GetAddrInfoW() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API

    这是因为新版本VS不支援该函数,需要修改下图中SDL检查 为 “否”

  • 相关阅读:
    JQuery的Dom操作
    JQuer的简单应用
    JSBom联合Dom的应用
    Bom—浏览器对象模型
    正则表达式(其实就是预习)
    Js关于表单的事件应用
    JavaScript事件练习
    微信小程序实现微信登录
    Azure 数据资源管理器 -- 当 ADX 遇上 ML
    多快好省 -- Azure VMSS AI 推理篇
  • 原文地址:https://www.cnblogs.com/gohikings/p/11819288.html
Copyright © 2011-2022 走看看