获取计算机的名称(方法二)

第二种方法使用gethostname,需要使用WinSock。

 

#include <WinSock2.h> #include <stdio.h> #pragma comment(lib, "Ws2_32.lib") #define INFO_BUFFER_SIZE 100 int main() { WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ return 1; } /* Confirm that the WinSock DLL supports 2.2.*/ /* Note that if the DLL supports versions greater */ /* than 2.2 in addition to 2.2, it will still return */ /* 2.2 in wVersion since that is the version we */ /* requested. */ if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { /* Tell the user that we could not find a usable */ /* WinSock DLL. */ WSACleanup( ); return 1; } /* The WinSock DLL is acceptable. Proceed. */ char infoBuf[INFO_BUFFER_SIZE]; //If no error occurs, gethostname returns zero. Otherwise, it returns SOCKET_ERROR if (gethostname(infoBuf, INFO_BUFFER_SIZE)==SOCKET_ERROR) { printf("SOCKET_ERROR/n"); } printf("nComputer name: %s/n", infoBuf); return 0; }

 

 

运行结果:

 

这种方法获取的计算机名吃小写的。

你可能感兴趣的:(获取计算机的名称(方法二))