netproperty

//NetProperty.h

#pragma once
#include <string>
#include <iostream>
class CNetProperty
{
public:
 CNetProperty(void);
 ~CNetProperty(void);
 char * GetLocalIp();
 bool IniSocket();
 void CLeanSocket();

};

//NetProperty.cpp

#include "stdafx.h"
#include "NetProperty.h"

#include <Winsock2.h>
#include <string>
#include <iostream>
#pragma comment(lib, "WS2_32.lib")

using namespace std;

CNetProperty::CNetProperty(void)
{
}

CNetProperty::~CNetProperty(void)
{
}
char * CNetProperty::GetLocalIp()
{
 IniSocket();
 //通過本機主機名.
 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)
 {
  //sa = new in_addr;
  //循環獲取本地主機名
  for (int i = 0; hp->h_addr_list[i]; i++)
  {
   memcpy (&sa, hp->h_addr_list[i],hp->h_length);
   buf = inet_ntoa(sa);
   break;
  }
 } 
 CLeanSocket();
 return buf;
}
bool CNetProperty::IniSocket()
{
 //Socket初始化部分
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;
 wVersionRequested = MAKEWORD(2, 2);
 err = WSAStartup(wVersionRequested, &wsaData);
 if (err != 0)
 {
  cout << "Initialize failed!" << endl;
  return FALSE;
 }

 if (LOBYTE( wsaData.wVersion ) != 2 ||
  HIBYTE( wsaData.wVersion ) != 2)
 {
  WSACleanup( );
  cout << "Initialize failed!" << endl;
  return FALSE;
 }
 return TRUE;
}

void CNetProperty::CLeanSocket()
{
 WSACleanup();
}

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章