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检查 为 “否”

  • 相关阅读:
    BZOJ4569: [Scoi2016]萌萌哒
    BZOJ4566: [Haoi2016]找相同字符
    BZOJ4556: [Tjoi2016&Heoi2016]字符串
    BZOJ4545: DQS的trie
    BZOJ4458: GTY的OJ
    Codeforces Beta Round #19E. Fairy
    不确定性推理
    朴素贝叶斯
    对抗搜索
    struct
  • 原文地址:https://www.cnblogs.com/gohikings/p/11819288.html
Copyright © 2011-2022 走看看