获得本地IP

来源:互联网 发布:火箭炮升级数据 编辑:程序博客网 时间:2024/05/14 23:24

  char szHostName[128]; // 本地主机名
   memset(szHostName,'0',128);
   
   char szHostIP[30];
   memset(szHostIP,'0',30);
   
   CString m_IP,m_LocalIP;
   if( gethostname(szHostName,128) == 0)          
   {         
    struct hostent *pHost;                          
    pHost = gethostbyname(szHostName);                      
    
    // 考虑获取第一个网卡的IP.
    for(int client = 0; pHost != NULL && pHost->h_addr_list[client] != NULL; client++)
    {
     struct in_addr addr;
     memcpy(&addr, pHost->h_addr_list[client], sizeof(struct in_addr));
     sprintf(szHostIP,"%s",inet_ntoa(addr));
    }
   }
   m_dwIP = inet_addr(szHostIP);

inet_addr 返回DWORD 类型值

szHostIP 为 “10.97.81.157”   m_dwIP 为2639356170 32位unsigned long 型,

将这个十进制的 2639356170  转成16进制 为 9D 51 61 0A  , 4个字节 ,将9D 51 61 0A  依次转成10进制 为 157,81,97,10

原创粉丝点击