您的位置:首页 > 理论基础

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

2009-10-13 10:47 211 查看
第二种方法使用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;

}


运行结果:



这种方法获取的计算机名吃小写的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: