分享

获得本机IP地址

 美美花花 2011-07-27
#include <Winsock2.h>
#include <string>
#include <iostream>
using namespace std;
#pragma comment(lib, "WS2_32.lib")
void main()
{
 //Socket初始化部分
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 wVersionRequested = MAKEWORD(2, 2);
 err = WSAStartup(wVersionRequested, &wsaData);
 if (err != 0)
 {
  cout << "Initialize failed!" << endl;
  return;
 }
 if (LOBYTE( wsaData.wVersion ) != 2 ||
  HIBYTE( wsaData.wVersion ) != 2)
 {
  WSACleanup( );
  cout << "Initialize failed!" << endl;
  return;
 }
 //通过本机主机名.
 char host_name[256];
 gethostname(host_name,sizeof(host_name));
 struct hostent  *hp;
 struct in_addr  sa;
 char    *buf;
 hp = gethostbyname(host_name);
 if (hp != NULL)
 {
  //循环获取本地主机名
  for (int i = 0; hp->h_addr_list[i]; i++)
  {
   memcpy (&sa, hp->h_addr_list[i],hp->h_length);
   buf = inet_ntoa(sa);
   cout << "The host IP is:" << buf << endl;
  }
 }
 WSACleanup();
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多