VC----如何自动获取本机IP地址?

1
#include
#include
#pragma comment(lib,"ws2_32.lib")

int doit(int, char **)
{
 char host_name[255];
 //获取本地主机名称
 if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR)
 {
  printf("Error %d when getting local host name.n", WSAGetLastError());
  return 1;
 }

 printf("Host name is: %s\n", host_name);
 //从主机名数据库中得到对应的“主机”
 struct hostent *phe = gethostbyname(host_name);
 if (phe == 0)
 {
  printf("Yow! Bad host lookup.");
  return 1;
 }
 //循环得出本地机器所有IP地址
 for (int i = 0; phe->h_addr_list[i] != 0; ++i)
 {
  struct in_addr addr;
  memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
  printf("Address %d : %s\n" , i, inet_ntoa(addr));
 }

 return 0;
}

int main(int argc, char *argv[])
{
 WSAData wsaData;
 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
 {
  system("pause");
  return 255;
 }
 int retval = doit(argc, argv);
 WSACleanup();
 system("pause");
 return retval;
}


2
//#include
//连接 ws2_32.lib
void CCWebClientDlg::InitSocket()
{
 WORD  wVersionRequested;
 WSADATA  wsaData;
 char  name[255];
 CString  ip;
 int err;  PHOSTENT  hostinfo;
 wVersionRequested  =  MAKEWORD( 1, 1 );//版本号1.1 
 //1.加载套接字库
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 )
 {
  return;
 }  //判断是否我们请求的winsocket版本,如果不是
 //则调用WSACleanup终止winsocket的使用并返回              if ( LOBYTE( wsaData.wVersion ) != 1 ||
 HIBYTE( wsaData.wVersion ) != 1 )
 {
  WSACleanup( );
  return;
 }///...if  if  ( err  ==  0  )
 {

  if(  gethostname  (  name,  sizeof(name))  ==  0)
  {
   if((hostinfo  =  gethostbyname(name))  !=  NULL)
   { 
    ip  =  inet_ntoa  (*(struct  in_addr  *)*hostinfo->h_addr_list);
   }
  }

  WSACleanup();
 }

 SetDlgItemText(IDC_EDIT_PORT,name);//name里是本机名
 SetDlgItemText(IDC_IPADDRESS1,ip);  //ip中是本机IP   

}

3
需要包含:#include
添加:IPHlpApi.lib

DWORD dwResult;
ULONG OutBufLen;
IP_ADAPTER_INFO AdapterInfo;
OutBufLen = sizeof(IP_ADAPTER_INFO);
dwResult = GetAdaptersInfo(&AdapterInfo,&OutBufLen);
//网卡地址:AdapterInfo.AdapterName // IP:   AdapterInfo.IpAddressList.IpAddress //子网掩码:  AdapterInfo.IpAddressList.IpMask FIXED_INFO fixed_info; OutBufLen = sizeof(FIXED_INFO); GetNetworkParams(&fixed_info,&OutBufLen); //计算机名  fixed_info.HostName //DNS  fixed_info.DnsServerList.IpAddress

 

你可能感兴趣的:(Windows,C++,编程)