回 帖 发 新 帖 刷新版面

主题:[转帖]如何用C++获得某台机器的IP地址

// getip1.cpp
//
// 本程序报告本机上每一块网卡的IP地址
// 命令行编译命令为:
//
// cl getip1.cpp wsock32.lib
//
// 请一定要在环境变量中正确指定LIB库的路径;可以运行vcvars32.bat
//
#include <winsock.h>
#include <wsipx.h>
#include <wsnwlink.h>
#include <stdio.h>

int main()
{
   ////////////////
   // 初始化 Windows sockets API. 要求版本为 version 1.1
   //
   WORD wVersionRequested = MAKEWORD(1, 1);
   WSADATA wsaData;
   if (WSAStartup(wVersionRequested, &wsaData)) {
      printf("WSAStartup failed %s\n", WSAGetLastError());
      return -1;
   }

   //////////////////
   // 获得主机名.
   //
   char hostname[256];
   int res = gethostname(hostname, sizeof(hostname));
   if (res != 0) {
      printf("Error: %u\n", WSAGetLastError());
      return -1;
   }
   printf("hostname=%s\n", hostname);
   ////////////////
   // 根据主机名获取主机信息.
   //
   hostent* pHostent = gethostbyname(hostname);
   if (pHostent==NULL) {
      printf("Error: %u\n", WSAGetLastError());
      return -1;
   }
   //////////////////
   // 解析返回的hostent信息.
   //
   hostent& he = *pHostent;
   printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
      he.h_name, he.h_aliases, he.h_addrtype, he.h_length);

   sockaddr_in sa;
   for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
      memcpy ( &sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
      // 输出机器的IP地址.
      printf("Address: %s\n", inet_ntoa(sa.sin_addr)); // 显示地址串
   }
   //////////////////
   // 终止 Windows sockets API
   //
   WSACleanup();
   return 0;
}

回复列表 (共13个回复)

11 楼

这个程序看不太懂,能不能解释一下

12 楼

多谢大家的讨论。
由于是控制台程序,建议在Dev-C++中运行。我在Dev-C++ 5 beta 9.2中运行通过。

13 楼

对于这个程序,我还会发贴补充。

我来回复

您尚未登录,请登录后再回复。点此登录或注册