获取本机名和IP地址

 1 #include "stdafx.h"
 2 #include <Winsock2.h>
 3 #include <iostream>
 4 //using namespace std;
 5 
 6 #pragma comment(lib, "ws2_32.lib")
 7 
 8 int _tmain(int argc, _TCHAR* argv[])
 9 {
10     WORD wVersionRequested;
11     WSADATA wsaData;
12     wVersionRequested = MAKEWORD( 22 );
13     WSAStartup( wVersionRequested, &wsaData );
14 
15     char szName[255];
16     memset(szName,0,255);
17     if(gethostname(szName,255)==SOCKET_ERROR)
18       {
19               //错误处理
20           std::cout<<"出现错误"<<std::endl;
21           return 1;
22       }
23 
24     hostent* host;
25     char* ip;
26     host = gethostbyname(szName);
27     if(host->h_addr_list[0])
28     {
29         struct in_addr addr;
30         addr = *(struct in_addr*)host->h_addr_list[0];
31         //获得标准IP地址
32         ip=inet_ntoa(addr);
33     }
34 
35     std::cout<<"主机名是: "<< szName<<std::endl;
36     std::cout<<"IP地址是: "<<ip<<std::endl;
37     //std::cout<<"hello world"<<std::endl;
38     return 0;
39 }
posted on 2008-08-18 16:14  风荷小筑  阅读(307)  评论(0)    收藏  举报