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