#include "stdafx.h"
#include <iostream>
#include <Winsock2.h>
#pragma comment( lib, "ws2_32.lib" )
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//
// 初始化 套接字
int err;
WORD wVersionRequested;
WSADATA wsaData;
/* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
wVersionRequested = MAKEWORD(2, 2);
err = WSAStartup(wVersionRequested, &wsaData);
if (err != 0) {
/* Tell the user that we could not find a usable */
/* Winsock DLL. */
printf("WSAStartup failed with error: %d\n", err);
return 1;
}
//
int errorCode;
char name[300] = {0};
if (::gethostname(name, 300) == 0) // 注意:调用这个函数的时候,一定要初始化套接字
{
cout << name << endl; // 输出: benben_wsx-PC
PHOSTENT hostinfo;
if ((hostinfo = gethostbyname(name)) != NULL)
{
LPCSTR pIP = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
cout << "IP: " << pIP << endl; // 输出: 192.168.**.**
}
}
else
{
errorCode = WSAGetLastError();
cout << "errorCode: " << errorCode << endl;
}
WSACleanup();
return 0;
}