zoukankan      html  css  js  c++  java
  • 获取本机IP


      1 // ConsoleApplication12.cpp : This file contains the 'main' function. Program execution begins and ends there.
      2 //
      3 #include <winsock2.h>
      4 #include <windows.h>
      5 #include <WS2tcpip.h>
      6 #include <IPTypes.h>
      7 #include <iphlpapi.h>
      8 #include <iostream>
      9 
     10 #pragma comment(lib, "ws2_32.lib")
     11 #pragma comment(lib, "IPHLPAPI.lib")
     12 
     13 using namespace std;
     14 
     15 
     16 
     17 void get_local_ip()
     18 {
     19     ULONG rCode = 0;
     20     ULONG Length = sizeof(IP_ADAPTER_INFO);
     21     std::string IpAddr;
     22 
     23     PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
     24 
     25     rCode = GetAdaptersInfo(pIpAdapterInfo, &Length);
     26 
     27     if (ERROR_BUFFER_OVERFLOW == rCode) {
     28         //重新申请内存空间用来存储所有网卡信息        
     29         delete pIpAdapterInfo;
     30         pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[Length];
     31         rCode = GetAdaptersInfo(pIpAdapterInfo, &Length);
     32     }
     33     if (rCode == ERROR_SUCCESS) {
     34         //返回第一张网卡的第一个IP地址
     35         for (UINT i = 0; i < 16; i++) {
     36             if (!pIpAdapterInfo->IpAddressList.IpAddress.String[i])
     37                 break;
     38 
     39             IpAddr += pIpAdapterInfo->IpAddressList.IpAddress.String[i];
     40 
     41         }
     42     }
     43     if (pIpAdapterInfo) {
     44         delete pIpAdapterInfo;
     45     }
     46     cout << IpAddr.c_str() << endl;
     47     //return IpAddr;
     48 }
     49 
     50 
     51 int main()
     52 {
     53     get_local_ip();
     54     //cout << ip.c_str() << endl;
     55     std::cout << "Hello World!
    " << endl;
     56     getchar();
     57 }
     58 
    PS:会笑的人,运气通常都会比别人好。
  • 相关阅读:
    线程的用法
    提高VS2010的性能,VS2010不再卡
    win7 远程桌面最大化快捷键
    java类加载器
    Class类
    JDBC获得oracle数据库主键值
    Zookeeper入门基础知识
    项目js总结
    jdk8 stream项目使用
    全局请求参数去除空格
  • 原文地址:https://www.cnblogs.com/thinkinc999/p/13455007.html
Copyright © 2011-2022 走看看