#pragma comment (lib,"ws2_32.lib")
#include<winsock2.h>
#include<iostream>
using namespace std;
int main()
{
// winsock注册
WSAData wsaData;
WORD wVersionReq=MAKEWORD(1,2);
int error=WSAStartup( wVersionReq, &wsaData);
if(error!=0)
cout<<"Fail"<<endl;
else cout<<"success"<<endl;
#define BUFSIZE 1024 //定义默认缓冲区大小
/* 变量声明 */
LPTSTR lpszSystemInfo; // 声明一个字符串指针变量
DWORD cchBuff = BUFSIZE;//定义缓冲区大小
TCHAR tchBuffer[BUFSIZE];// 声明一个串缓冲区
lpszSystemInfo = tchBuffer;//将指针指向串缓冲区tchBuffer
// 调用GetComputerName获取本地计算机名称
if( GetComputerName(lpszSystemInfo, &cchBuff) )
{
cout<<"本地计算机名称(GetComputerName): "<<lpszSystemInfo<<endl;
}
// 调用gethostname获取本地计算机名称
if( gethostname(lpszSystemInfo, cchBuff) )
{
cout<<"本地计算机名称(gethostname): "<<lpszSystemInfo<<endl;
}
//获取主机的IP地址
struct hostent *p_HostEnt;
p_HostEnt = gethostbyname(lpszSystemInfo);
if(p_HostEnt != NULL)
{
char Hostaddress[20]; // 主机IP地址
wsprintf( Hostaddress, " %d. %d. %d. %d",
( p_HostEnt->h_addr_list[0][0] & 0x00ff ),
( p_HostEnt->h_addr_list[0][1] & 0x00ff ),
( p_HostEnt->h_addr_list[0][2] & 0x00ff ),
( p_HostEnt->h_addr_list[0][3] & 0x00ff ) );
cout<<"本机IP地址:"<<Hostaddress<<endl;
}
//注销winsock
WSACleanup();
system("pause");
}
效果图: