获取主机名称和ip,用户名

来源:互联网 发布:阿里云开启3306端口 编辑:程序博客网 时间:2024/06/06 18:27
#include <iostream>#include <string>#include <winsock2.h>#pragma comment(lib,"ws2_32.lib")using namespace std;int main(int argc, char* argv[]){string ip_list;char PCnameBuffer[128];    //获得本地计算机名WSAData data;              //初始化:如果不初始化,以下代码将无法执行if(WSAStartup(MAKEWORD(1,1),&data)!=0)  {  cout<<"初始化错误,无法获取主机信息..."<<endl;  }  else{if(0==gethostname(PCnameBuffer,128))  {  struct hostent* pHost;  //获得本地IP地址pHost=gethostbyname(PCnameBuffer);  //pHost返回的是指向主机的列表for (int i=0;pHost!=NULL&&pHost->h_addr_list[i]!=NULL;i++)  {string tem = inet_ntoa(*(struct in_addr *)pHost->h_addr_list[i]);ip_list += tem;ip_list += "\n";}  }  else  {  cout<<"获取主机信息失败..."<<endl ;  }}  cout<<PCnameBuffer<<endl;cout<<ip_list<<endl;getchar();return 0;  }


获取用户名:

#include <iostream>#include <afx.h>#pragma comment(lib,"Advapi32.lib")using namespace std;int main(){CString strUserName; LPTSTR szBuffer=new wchar_t[300];      DWORD dwSize=300;      GetUserName(szBuffer,&dwSize);      strUserName=szBuffer;  delete szBuffer; const size_t newsizew = (strUserName.GetLength() + 1)*2; //  char *ch = new char[newsizew];  WideCharToMultiByte(CP_OEMCP,NULL,strUserName,-1,ch,newsizew,0,NULL);// m_cstr --> ch cout<<ch<<endl;return 0;}