获取本机名和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( 2, 2 );
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 }
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( 2, 2 );
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 }