//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();
}