示例#1
0
int main( int argc, char **argv ) {
    ULONG OutBufLen = 0;
    PFIXED_INFO pFixedInfo;
    PIP_ADDR_STRING Addr;

    GetNetworkParams(NULL, &OutBufLen);
    pFixedInfo = malloc(OutBufLen);
    if (!pFixedInfo) {
        printf( "Failed to alloc %d bytes.\n", (int)OutBufLen );
        return 1;
    }

    printf( "%d Bytes allocated\n", (int)OutBufLen );

    GetNetworkParams(pFixedInfo,&OutBufLen);

    for( Addr = &pFixedInfo->DnsServerList;
            Addr;
            Addr = Addr->Next ) {
        printf( "%c%s\n",
                Addr == pFixedInfo->CurrentDnsServer ? '*' : ' ',
                Addr->IpAddress.String );
    }

    free( pFixedInfo );
    return 0;
}
示例#2
0
文件: util.c 项目: Gexecho/andiodine
char *
get_resolvconf_addr()
{
	static char addr[16];
	char *rv;
#ifndef WINDOWS32
	char buf[80];
	FILE *fp;
#ifdef ANDROID
	fp = popen("getprop net.dns1", "r");
	if (fp == NULL)
		err(1, "getprop net.dns1 failed");
	if (fgets(buf, sizeof(buf), fp) == NULL)
		err(1, "read getprop net.dns1 failed");
	if (sscanf(buf, "%15s", addr) == 1)
		rv = addr;
	pclose(fp);
#else

	rv = NULL;

	if ((fp = fopen("/etc/resolv.conf", "r")) == NULL)
		err(1, "/etc/resolv.conf");

	while (feof(fp) == 0) {
		fgets(buf, sizeof(buf), fp);

		if (sscanf(buf, "nameserver %15s", addr) == 1) {
			rv = addr;
			break;
		}
	}

	fclose(fp);
#endif
#else /* !WINDOWS32 */
	FIXED_INFO  *fixed_info;
	ULONG       buflen;
	DWORD       ret;

	rv = NULL;
	fixed_info = malloc(sizeof(FIXED_INFO));
	buflen = sizeof(FIXED_INFO);

	if (GetNetworkParams(fixed_info, &buflen) == ERROR_BUFFER_OVERFLOW) {
		/* official ugly api workaround */
		free(fixed_info);
		fixed_info = malloc(buflen);
	}

	ret = GetNetworkParams(fixed_info, &buflen);
	if (ret == NO_ERROR) {
		strncpy(addr, fixed_info->DnsServerList.IpAddress.String, sizeof(addr));
		addr[15] = 0;
		rv = addr;
	}
	free(fixed_info);
#endif
	return rv;
}
示例#3
0
int slirp_get_system_dns_servers(void)
{
    FIXED_INFO *FixedInfo=NULL;
    ULONG    BufLen;
    DWORD    ret;
    IP_ADDR_STRING *pIPAddr;

    if (dns_addr_count > 0)
        return dns_addr_count;

    FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
    BufLen = sizeof(FIXED_INFO);

    if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {
        if (FixedInfo) {
            GlobalFree(FixedInfo);
            FixedInfo = NULL;
        }
        FixedInfo = GlobalAlloc(GPTR, BufLen);
    }

    if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {
        printf("GetNetworkParams failed. ret = %08x\n", (u_int)ret );
        if (FixedInfo) {
            GlobalFree(FixedInfo);
            FixedInfo = NULL;
        }
        return -1;
    }

    D( "DNS Servers:");
    pIPAddr = &(FixedInfo->DnsServerList);
    while (pIPAddr && dns_addr_count < DNS_ADDR_MAX) {
        uint32_t  ip;
        D( "  %s", pIPAddr->IpAddress.String );
        if (inet_strtoip(pIPAddr->IpAddress.String, &ip) == 0) {
            if (ip == loopback_addr_ip)
                ip = our_addr_ip;
            if (dns_addr_count < DNS_ADDR_MAX)
                dns_addr[dns_addr_count++] = ip;
        }
        pIPAddr = pIPAddr->Next;
    }

    if (FixedInfo) {
        GlobalFree(FixedInfo);
        FixedInfo = NULL;
    }
    if (dns_addr_count <= 0)
        return -1;

    return dns_addr_count;
}
///////////////////////////////////////////
//
// gets the domain name
//
// returns:  0 on failure  1 on success
//
//
//////////////////////////////////////////
int getWindowsDomainName(char *domain_name)
{
        DWORD Err;
        DWORD NetworkInfoSize;
        PFIXED_INFO pNetworkInfo;

        int retval = 0;

        *domain_name = '\0';

        if (isIPHLPAvail())  //inits iphlpapi and returns true if dll loaded
        {
                if (GetNetworkParams != NULL)
                {
                        //force size to 0 so the GetNetworkParams gets the correct size
                        NetworkInfoSize = 0;
                        if( ( Err = GetNetworkParams( NULL, &NetworkInfoSize ) ) != 0 )
                        {
                                if( Err != ERROR_BUFFER_OVERFLOW )
                                {
                                        printf( "GetNetworkParams sizing failed with error %d\n", Err );
                                        return 0;
                                }
                        }

                        // Allocate memory from sizing information
                        if( ( pNetworkInfo = (PFIXED_INFO)GlobalAlloc( GPTR, NetworkInfoSize ) ) == NULL )
                        {
                                printf( "Memory allocation error\n" );
                                return 0;
                        }

                        // Get actual network params
                        if( ( Err = GetNetworkParams( pNetworkInfo, &NetworkInfoSize ) ) != 0 )
                        {
                                printf( "GetNetworkParams failed with error %d\n", Err );
                                return 0;
                        }

                        strcpy(domain_name, pNetworkInfo->DomainName);

                        //free the memory
                        GlobalFree(pNetworkInfo);   // handle to global memory object

                }

        }

        return retval;
}
示例#5
0
str_list_t DLLCALL getNameServerList(void)
{
#ifdef __unix__	/* Look up DNS server address */
	FILE*	fp;
	char*	p;
	char	str[128];
	str_list_t	list;

	if((list=strListInit())==NULL)
		return(NULL);
	if((fp=fopen("/etc/resolv.conf","r"))!=NULL) {
		while(!feof(fp)) {
			if(fgets(str,sizeof(str),fp)==NULL)
				break;
			truncsp(str);
			p=str;
			SKIP_WHITESPACE(p);
			if(strnicmp(p,"nameserver",10)!=0) /* no match */
				continue;
			FIND_WHITESPACE(p);	/* skip "nameserver" */
			SKIP_WHITESPACE(p);	/* skip more white-space */
			strListPush(&list,p);
		}
		fclose(fp);
	}
	return(list);

#elif defined(_WIN32)
	FIXED_INFO* FixedInfo=NULL;
	ULONG    	FixedInfoLen=0;
	IP_ADDR_STRING* ip;
	str_list_t	list;

	if((list=strListInit())==NULL)
		return(NULL);
	if(GetNetworkParams(FixedInfo,&FixedInfoLen) == ERROR_BUFFER_OVERFLOW) {
        FixedInfo=(FIXED_INFO*)malloc(FixedInfoLen);
		if(GetNetworkParams(FixedInfo,&FixedInfoLen) == ERROR_SUCCESS) {
			ip=&FixedInfo->DnsServerList;
			for(; ip!=NULL; ip=ip->Next)
				strListPush(&list,ip->IpAddress.String);
		}
        if(FixedInfo!=NULL)
            free(FixedInfo);
    }
	return(list);
#else
	#error "Need a get_nameserver() implementation for this platform"
#endif
}
示例#6
0
static int get_dns_addr(struct in_addr *pdns_addr)
{
    FIXED_INFO *FixedInfo=NULL;
    ULONG    BufLen;
    DWORD    ret;
    IP_ADDR_STRING *pIPAddr;
    struct in_addr tmp_addr;
    
    FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
    BufLen = sizeof(FIXED_INFO);
   
    if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {
        if (FixedInfo) {
            GlobalFree(FixedInfo);
            FixedInfo = NULL;
        }
        FixedInfo = GlobalAlloc(GPTR, BufLen);
    }
	
    if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {
        printf("GetNetworkParams failed. ret = %08x\n", (u_int)ret );
        if (FixedInfo) {
            GlobalFree(FixedInfo);
            FixedInfo = NULL;
        }
        return -1;
    }
     
    pIPAddr = &(FixedInfo->DnsServerList);
    inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
    *pdns_addr = tmp_addr;
#if 0
    printf( "DNS Servers:\n" );
    printf( "DNS Addr:%s\n", pIPAddr->IpAddress.String );
    
    pIPAddr = FixedInfo -> DnsServerList.Next;
    while ( pIPAddr ) {
            printf( "DNS Addr:%s\n", pIPAddr ->IpAddress.String );
            pIPAddr = pIPAddr ->Next;
    }
#endif
    if (FixedInfo) {
        GlobalFree(FixedInfo);
        FixedInfo = NULL;
    }
    return 0;
}
/*
Note: Ancient PSDK required in order to build a W98 target.
*/
bool GetDNSNetworkParams(std::vector<std::string> &vecLocalDnsIp)
{
	bool bResult = false;
	FIXED_INFO *pFixdInfo = NULL;
	ULONG ulOutBufLen;
	DWORD dwRetVal;
	IP_ADDR_STRING *pIPAddr = NULL;
	do 
	{
		dwRetVal = GetNetworkParams(pFixdInfo, &ulOutBufLen);
		if(ERROR_BUFFER_OVERFLOW != dwRetVal && ERROR_SUCCESS != dwRetVal)
			break;

		if(ERROR_BUFFER_OVERFLOW == dwRetVal)
		{
			pFixdInfo = (PFIXED_INFO)malloc(ulOutBufLen);
			if(NULL == pFixdInfo)
				break;
		}

		dwRetVal = GetNetworkParams(pFixdInfo, &ulOutBufLen);

		if(ERROR_SUCCESS == dwRetVal)
		{
			for(pIPAddr = &pFixdInfo->DnsServerList; pIPAddr; pIPAddr = pIPAddr->Next)
			{
				vecLocalDnsIp.push_back(pIPAddr->IpAddress.String);
			}
		}

		if(!vecLocalDnsIp.empty())
			bResult = true;
	} while (false);

	if(NULL != pFixdInfo)
	{
		free(pFixdInfo);
		pFixdInfo = NULL;
	}

	return bResult;
}
示例#8
0
vector<string> DNS::getDNSServer(void)
{
	// MSDN sample code
	FIXED_INFO *FixedInfo;
	ULONG    ulOutBufLen;
	DWORD    dwRetVal;
	IP_ADDR_STRING * pIPAddr;

	ulOutBufLen = sizeof(FIXED_INFO);
	FixedInfo = (FIXED_INFO *) GlobalAlloc( GPTR, sizeof( FIXED_INFO ) );
	ulOutBufLen = sizeof( FIXED_INFO );

	if(ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &ulOutBufLen)) {
		GlobalFree( FixedInfo );
		FixedInfo = (FIXED_INFO *)GlobalAlloc( GPTR, ulOutBufLen );
	}

	if ( dwRetVal = GetNetworkParams( FixedInfo, &ulOutBufLen ) ) {
		printf( "Call to GetNetworkParams failed. Return Value: %08x\n", dwRetVal );
	}
	else {
		//printf( "Host Name: %s\n", FixedInfo->HostName );
		//printf( "Domain Name: %s\n", FixedInfo->DomainName );

		//printf( "DNS Servers:\n" );
		//printf( "\t%s\n", FixedInfo->DnsServerList.IpAddress.String);
	    
		vector<string> hosts;
		hosts.push_back(FixedInfo->DnsServerList.IpAddress.String);
		pIPAddr = FixedInfo->DnsServerList.Next;
		while ( pIPAddr ) {
			hosts.push_back(pIPAddr ->IpAddress.String);
			//printf( "\t%s\n", pIPAddr ->IpAddress.String);
			pIPAddr = pIPAddr ->Next;
		}	
		return hosts;
	}

	GlobalFree (FixedInfo);
}
示例#9
0
std::vector<boost::asio::ip::address> getServer() {
  FIXED_INFO *pFixedInfo;
  ULONG ulOutBufLen;
  DWORD dwRetVal;
  IP_ADDR_STRING *pIPAddr;
  std::vector<boost::asio::ip::address> server;
  
  //boost::shared_ptr<FIXED_INFO> pFixedInfo (new(sizeof(FIXED_INFO));
  pFixedInfo = (FIXED_INFO *) malloc (sizeof(FIXED_INFO));
  ulOutBufLen = sizeof (FIXED_INFO);
  
  // get the size of pFixedInfo
  GetNetworkParams (pFixedInfo, &ulOutBufLen);
  free (pFixedInfo);
  
  // get actual data
  pFixedInfo = (FIXED_INFO *) malloc (ulOutBufLen);
  dwRetVal = GetNetworkParams (pFixedInfo, &ulOutBufLen);
  if (dwRetVal == NO_ERROR) {
    
    server.push_back (boost::asio::ip::address::from_string (
      pFixedInfo->DnsServerList.IpAddress.String));

    pIPAddr = pFixedInfo->DnsServerList.Next;
    while (pIPAddr) {
      server.push_back (boost::asio::ip::address::from_string (
        pIPAddr->IpAddress.String));
      pIPAddr = pIPAddr->Next;
    }
  } else {
     printf("GetNetworkParams failed with error: %d\n", dwRetVal);
  }

  free (pFixedInfo);
  
  return server;
}
示例#10
0
int
ub_ctx_resolvconf(struct ub_ctx* ctx, char* fname)
{
    FILE* in;
    int numserv = 0;
    char buf[1024];
    char* parse, *addr;
    int r;

    if(fname == NULL) {
#if !defined(UB_ON_WINDOWS) || !defined(HAVE_WINDOWS_H)
        fname = "/etc/resolv.conf";
#else
        FIXED_INFO *info;
        ULONG buflen = sizeof(*info);
        IP_ADDR_STRING *ptr;

        info = (FIXED_INFO *) malloc(sizeof (FIXED_INFO));
        if (info == NULL)
            return UB_READFILE;

        if (GetNetworkParams(info, &buflen) == ERROR_BUFFER_OVERFLOW) {
            free(info);
            info = (FIXED_INFO *) malloc(buflen);
            if (info == NULL)
                return UB_READFILE;
        }

        if (GetNetworkParams(info, &buflen) == NO_ERROR) {
            int retval=0;
            ptr = &(info->DnsServerList);
            while (ptr) {
                numserv++;
                if((retval=ub_ctx_set_fwd(ctx,
                                          ptr->IpAddress.String)!=0)) {
                    free(info);
                    return retval;
                }
                ptr = ptr->Next;
            }
            free(info);
            if (numserv==0)
                return UB_READFILE;
            return UB_NOERROR;
        }
        free(info);
        return UB_READFILE;
#endif /* WINDOWS */
    }
    in = fopen(fname, "r");
    if(!in) {
        /* error in errno! perror(fname) */
        return UB_READFILE;
    }
    while(fgets(buf, (int)sizeof(buf), in)) {
        buf[sizeof(buf)-1] = 0;
        parse=buf;
        while(*parse == ' ' || *parse == '\t')
            parse++;
        if(strncmp(parse, "nameserver", 10) == 0) {
            numserv++;
            parse += 10; /* skip 'nameserver' */
            /* skip whitespace */
            while(*parse == ' ' || *parse == '\t')
                parse++;
            addr = parse;
            /* skip [0-9a-fA-F.:]*, i.e. IP4 and IP6 address */
            while(isxdigit(*parse) || *parse=='.' || *parse==':')
                parse++;
            /* terminate after the address, remove newline */
            *parse = 0;

            if((r = ub_ctx_set_fwd(ctx, addr)) != UB_NOERROR) {
                fclose(in);
                return r;
            }
        }
    }
    fclose(in);
    if(numserv == 0) {
        /* from resolv.conf(5) if none given, use localhost */
        return ub_ctx_set_fwd(ctx, "127.0.0.1");
    }
    return UB_NOERROR;
}
示例#11
0
bool NameServers(vector<IPV4Address> *name_servers) {
#if HAVE_DECL_RES_NINIT
  struct __res_state res;
  memset(&res, 0, sizeof(struct __res_state));

  // Init the resolver info each time so it's always current for the RDM
  // responders in case we've set it via RDM too
  if (res_ninit(&res) != 0) {
    OLA_WARN << "Error getting nameservers via res_ninit";
    return false;
  }

  for (int32_t i = 0; i < res.nscount; i++) {
    IPV4Address addr = IPV4Address(res.nsaddr_list[i].sin_addr.s_addr);
    OLA_DEBUG << "Found Nameserver " << i << ": " << addr;
    name_servers->push_back(addr);
  }

  res_nclose(&res);
#elif defined(_WIN32)
  ULONG size = sizeof(FIXED_INFO);
  PFIXED_INFO fixed_info = NULL;
  while (1) {
    fixed_info = reinterpret_cast<PFIXED_INFO>(new uint8_t[size]);
    DWORD result = GetNetworkParams(fixed_info, &size);
    if (result == ERROR_SUCCESS) {
      break;
    }

    if (result != ERROR_BUFFER_OVERFLOW) {
      OLA_WARN << "GetNetworkParams failed with: " << GetLastError();
      return false;
    }

    delete[] fixed_info;
  }

  IP_ADDR_STRING* addr = &(fixed_info->DnsServerList);
  for (; addr; addr = addr->Next) {
    IPV4Address ipv4addr = IPV4Address(inet_addr(addr->IpAddress.String));
    OLA_DEBUG << "Found nameserver: " << ipv4addr;
    name_servers->push_back(ipv4addr);
  }

  delete[] fixed_info;
#else
  // Init the resolver info each time so it's always current for the RDM
  // responders in case we've set it via RDM too
  if (res_init() != 0) {
    OLA_WARN << "Error getting nameservers via res_init";
    return false;
  }

  for (int32_t i = 0; i < _res.nscount; i++) {
    IPV4Address addr = IPV4Address(_res.nsaddr_list[i].sin_addr.s_addr);
    OLA_DEBUG << "Found Nameserver " << i << ": " << addr;
    name_servers->push_back(addr);
  }
#endif

  return true;
}
示例#12
0
//
// Get Default Information (IP, GateWay, DNS, HostName, DHCP, etc..)
void GetWlanDefaultInformation(PBBS_ADAPTER_INFO pInformation)
{
	
	PIP_ADAPTER_INFO pAdapterInfo = NULL;
	PFIXED_INFO pNetworkParams = NULL;

	ULONG ulSizeAdapterInfo = 0;
	DWORD dwReturnvalueGetAdapterInfo = 0;
	TCHAR tszAdapterNameTemp[MAX_ADAPTER_NAME_LENGTH + 4] = {'\0',};
	ULONG uSizeNetworkParams = 0;
	DWORD dwReturnvalueGetNetworkParams;

	BOOL bFindWirelessAdapter = FALSE;

	pInformation->tszAdapterName[0] = L'\0';
	memset( pInformation, 0x0, sizeof(BBS_ADAPTER_INFO) );

	// -----------------------GetAdaptersInfo-----------------------------------------

	dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo );
	if ( dwReturnvalueGetAdapterInfo == ERROR_BUFFER_OVERFLOW)
	{
		if (!(pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo)))
		{
			return;
		}

		dwReturnvalueGetAdapterInfo = GetAdaptersInfo( pAdapterInfo, &ulSizeAdapterInfo);
		if (dwReturnvalueGetAdapterInfo != ERROR_SUCCESS)
		{
			free(pAdapterInfo);
			return;
		}

		while (pAdapterInfo != NULL)
		{
			mbstowcs( tszAdapterNameTemp, pAdapterInfo->AdapterName, MAX_ADAPTER_NAME_LENGTH + 4 );

			// Wireless 아답터 인지 확인
			// Nids의 OID_GEN_PHYSICAL_MEDIUM 로 NdisPhysicalMediumWirelessLan 임을 확인하는 방법이 있으나, 아답터 전원Off 상태에서는 조회 되지 않음
			// Summit 모듈도 확인하기 위해서, Wzctool은 사용하지 않음

			for(int i=0; i< sizeof(ManageableAdapters) / sizeof(ManageableAdapters[0]); i++)
			{
				if( _tcscmp(tszAdapterNameTemp, ManageableAdapters[i]) == 0 )
				{
					bFindWirelessAdapter = TRUE;
				}
			}

			if( bFindWirelessAdapter ) 
			{
				// Adapter Name
				_tcscpy(pInformation->tszAdapterName, tszAdapterNameTemp);

				// IPAddr
				mbstowcs( pInformation->tszIPAddr, pAdapterInfo->IpAddressList.IpAddress.String, sizeof(pAdapterInfo->IpAddressList.IpAddress.String) );

				// Subnet Mask
				mbstowcs( pInformation->tszSubNetMask, pAdapterInfo->IpAddressList.IpMask.String, sizeof(pAdapterInfo->IpAddressList.IpMask.String) );

				// Default GateWay
				mbstowcs( pInformation->tszDefaultGateWay, pAdapterInfo->GatewayList.IpAddress.String, sizeof(pAdapterInfo->GatewayList.IpAddress.String) );

				// Mac Address
				_stprintf( pInformation->tszMacAddr, _T("%02X:%02X:%02X:%02X:%02X:%02X"), pAdapterInfo->Address[0],pAdapterInfo->Address[1],pAdapterInfo->Address[2],pAdapterInfo->Address[3],pAdapterInfo->Address[4],pAdapterInfo->Address[5] );

				// DHCP Enabled
				pInformation->bDHCPEnabled = (BOOL)pAdapterInfo->DhcpEnabled;

				break;
			}
			pAdapterInfo = pAdapterInfo->Next;
		}
	}

	if(pAdapterInfo)
	{
		free(pAdapterInfo);
	}


	// ---------------------GetNetwork Params --------------------------

	dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams , &uSizeNetworkParams);
	if (dwReturnvalueGetNetworkParams == ERROR_BUFFER_OVERFLOW)
	{
		if (!(pNetworkParams = (PFIXED_INFO) malloc(uSizeNetworkParams)))
		{
			return;
		}

		dwReturnvalueGetNetworkParams = GetNetworkParams(pNetworkParams, &uSizeNetworkParams);
		if (dwReturnvalueGetNetworkParams != ERROR_SUCCESS)
		{
			free(pNetworkParams);
			return;
		}
	}

	// Host Name
	mbstowcs( pInformation->tszHostName, pNetworkParams->HostName, sizeof(pNetworkParams->HostName) );

	// Dns Server
	mbstowcs( pInformation->tszDnsAddr, pNetworkParams->DnsServerList.IpAddress.String, sizeof(pNetworkParams->DnsServerList.IpAddress.String) );


	if(pNetworkParams)
	{
		free(pNetworkParams);
	}

	return;
}
示例#13
0
int exec_iphelp_api_sample()
{
    /* Some general variables */
    ULONG ulOutBufLen;
    DWORD dwRetVal;
    unsigned int i;
  
    /* variables used for GetNetworkParams */
    FIXED_INFO *pFixedInfo;
    IP_ADDR_STRING *pIPAddr;

    /* variables used for GetAdapterInfo */
    IP_ADAPTER_INFO *pAdapterInfo;
    IP_ADAPTER_INFO *pAdapter;

    /* variables used to print DHCP time info */
    struct tm newtime;
    char buffer[32];
    errno_t error;

    /* variables used for GetInterfaceInfo */
    IP_INTERFACE_INFO *pInterfaceInfo;

    /* variables used for GetIpAddrTable */
    MIB_IPADDRTABLE *pIPAddrTable;
    DWORD dwSize;
    IN_ADDR IPAddr;
    //char *strIPAddr;
	char addr[16] = { 0 };
	std::string ip_str;

    /* variables used for AddIpAddress */
//    UINT iaIPAddress;
//    UINT imIPMask;
//    ULONG NTEContext;
//    ULONG NTEInstance;

    /* variables used for GetIpStatistics */
    MIB_IPSTATS *pStats;

    /* variables used for GetTcpStatistics */
    MIB_TCPSTATS *pTCPStats;

    printf("------------------------\n");
    printf("This is GetNetworkParams\n");
    printf("------------------------\n");

    pFixedInfo = (FIXED_INFO *) MALLOC(sizeof (FIXED_INFO));
    if (pFixedInfo == NULL) {
        printf("Error allocating memory needed to call GetNetworkParams\n");
        return 1;
    }
    ulOutBufLen = sizeof (FIXED_INFO);

    if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pFixedInfo);
        pFixedInfo = (FIXED_INFO *) MALLOC(ulOutBufLen);
        if (pFixedInfo == NULL) {
            printf("Error allocating memory needed to call GetNetworkParams\n");
            return 1;
        }
    }

	dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen);
    if (dwRetVal != NO_ERROR) 
	{
        printf("GetNetworkParams failed with error %d\n", dwRetVal);
        if (pFixedInfo)
            FREE(pFixedInfo);
        return 1;
    } else {
        printf("\tHost Name: %s\n", pFixedInfo->HostName);
        printf("\tDomain Name: %s\n", pFixedInfo->DomainName);
        printf("\tDNS Servers:\n");
        printf("\t\t%s\n", pFixedInfo->DnsServerList.IpAddress.String);

        pIPAddr = pFixedInfo->DnsServerList.Next;
        while (pIPAddr) {
            printf("\t\t%s\n", pIPAddr->IpAddress.String);
            pIPAddr = pIPAddr->Next;
        }

        printf("\tNode Type: ");
        switch (pFixedInfo->NodeType) {
        case 1:
            printf("%s\n", "Broadcast");
            break;
        case 2:
            printf("%s\n", "Peer to peer");
            break;
        case 4:
            printf("%s\n", "Mixed");
            break;
        case 8:
            printf("%s\n", "Hybrid");
            break;
        default:
            printf("\n");
        }

        printf("\tNetBIOS Scope ID: %s\n", pFixedInfo->ScopeId);

        if (pFixedInfo->EnableRouting)
            printf("\tIP Routing Enabled: Yes\n");
        else
            printf("\tIP Routing Enabled: No\n");

        if (pFixedInfo->EnableProxy)
            printf("\tWINS Proxy Enabled: Yes\n");
        else
            printf("\tWINS Proxy Enabled: No\n");

        if (pFixedInfo->EnableDns)
            printf("\tNetBIOS Resolution Uses DNS: Yes\n");
        else
            printf("\tNetBIOS Resolution Uses DNS: No\n");
    }

    /* Free allocated memory no longer needed */
    if (pFixedInfo) {
        FREE(pFixedInfo);
        pFixedInfo = NULL;
    }

    printf("------------------------\n");
    printf("This is GetAdaptersInfo\n");
    printf("------------------------\n");

    pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof (IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL) {
        printf("Error allocating memory needed to call GetAdapterInfo\n");
        return 1;
    }
    ulOutBufLen = sizeof (IP_ADAPTER_INFO);

    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen);
        if (pAdapterInfo == NULL) {
            printf("Error allocating memory needed to call GetAdapterInfo\n");
            return 1;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) != NO_ERROR) {
        printf("GetAdaptersInfo failed with error %d\n", dwRetVal);
        if (pAdapterInfo)
            FREE(pAdapterInfo);
        return 1;
    }

    pAdapter = pAdapterInfo;
    while (pAdapter) {
        printf("\tAdapter Name: \t%s\n", pAdapter->AdapterName);
        printf("\tAdapter Desc: \t%s\n", pAdapter->Description);
        printf("\tAdapter Addr: \t");
        for (i = 0; i < (int) pAdapter->AddressLength; i++) {
            if (i == (pAdapter->AddressLength - 1))
                printf("%.2X\n", (int) pAdapter->Address[i]);
            else
                printf("%.2X-", (int) pAdapter->Address[i]);
        }
        printf("\tIP Address: \t%s\n",
               pAdapter->IpAddressList.IpAddress.String);
        printf("\tIP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String);

        printf("\tGateway: \t%s\n", pAdapter->GatewayList.IpAddress.String);
        printf("\t***\n");

        if (pAdapter->DhcpEnabled) {
            printf("\tDHCP Enabled: \tYes\n");
            printf("\tDHCP Server: \t%s\n",
                   pAdapter->DhcpServer.IpAddress.String);

            printf("\tLease Obtained: ");
            /* Display local time */
            error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseObtained);
            if (error)
                printf("\tInvalid Argument to _localtime32_s\n");

            else {
                // Convert to an ASCII representation 
                error = asctime_s(buffer, 32, &newtime);
                if (error)
                    printf("Invalid Argument to asctime_s\n");
                else
                    /* asctime_s returns the string terminated by \n\0 */
                    printf("%s", buffer);
            }

            printf("\tLease Expires:  ");
            error = _localtime32_s(&newtime, (__time32_t*) &pAdapter->LeaseExpires);
            if (error)
                printf("Invalid Argument to _localtime32_s\n");
            else {
                // Convert to an ASCII representation 
                error = asctime_s(buffer, 32, &newtime);
                if (error)
                    printf("Invalid Argument to asctime_s\n");
                else
                    /* asctime_s returns the string terminated by \n\0 */
                    printf("%s", buffer);
            }
        } else
            printf("\tDHCP Enabled: \tNo\n");

        if (pAdapter->HaveWins) {
            printf("\tHave Wins: \tYes\n");
            printf("\tPrimary Wins Server: \t%s\n",
                   pAdapter->PrimaryWinsServer.IpAddress.String);
            printf("\tSecondary Wins Server: \t%s\n",
                   pAdapter->SecondaryWinsServer.IpAddress.String);
        } else
            printf("\tHave Wins: \tNo\n");

        printf("\n");
        pAdapter = pAdapter->Next;
    }

    printf("------------------------\n");
    printf("This is GetInterfaceInfo\n");
    printf("------------------------\n");

    pInterfaceInfo = (IP_INTERFACE_INFO *) MALLOC(sizeof (IP_INTERFACE_INFO));
    if (pInterfaceInfo == NULL) {
        printf("Error allocating memory needed to call GetInterfaceInfo\n");
        return 1;
    }
    ulOutBufLen = sizeof (IP_INTERFACE_INFO);
    if (GetInterfaceInfo(pInterfaceInfo, &ulOutBufLen) ==
        ERROR_INSUFFICIENT_BUFFER) {
        FREE(pInterfaceInfo);
        pInterfaceInfo = (IP_INTERFACE_INFO *) MALLOC(ulOutBufLen);
        if (pInterfaceInfo == NULL) {
            printf("Error allocating memory needed to call GetInterfaceInfo\n");
            return 1;
        }
        printf("\t The size needed for the output buffer ulLen = %ld\n",
               ulOutBufLen);
    }

    if ((dwRetVal = GetInterfaceInfo(pInterfaceInfo, &ulOutBufLen)) == NO_ERROR) {
        printf("\tNum Adapters: %ld\n\n", pInterfaceInfo->NumAdapters);
        for (i = 0; i < (unsigned int) pInterfaceInfo->NumAdapters; i++) {
            printf("\tAdapter Index[%d]: %ld\n", i,
                   pInterfaceInfo->Adapter[i].Index);
            printf("\tAdapter Name[%d]:  %ws\n\n", i,
                   pInterfaceInfo->Adapter[i].Name);
        }
        printf("GetInterfaceInfo call succeeded.\n");
    } else {
        LPVOID lpMsgBuf = NULL;

        if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
                          (LPTSTR) & lpMsgBuf, 0, NULL)) {
            printf("\tError: %s", (char*)lpMsgBuf);
        }
        LocalFree(lpMsgBuf);
    }

    ///* If DHCP enabled, release and renew the IP address */
    ///* THIS WORKS BUT IT TAKES A LONG TIME AND INTERRUPTS NET CONNECTIONS */
    //if (pAdapterInfo->DhcpEnabled && pInterfaceInfo->NumAdapters) {
    //    printf("Calling IpReleaseAddress for Adapter[%d]\n", 0);
    //    if ((dwRetVal =
    //         IpReleaseAddress(&pInterfaceInfo->Adapter[0])) == NO_ERROR) {
    //        printf("Ip Release succeeded.\n");
    //    }
    //    if ((dwRetVal =
    //         IpRenewAddress(&pInterfaceInfo->Adapter[0])) == NO_ERROR) {
    //        printf("Ip Renew succeeded.\n");
    //    }
    //}

    /* Free allocated memory no longer needed */
    if (pAdapterInfo) {
        FREE(pAdapterInfo);
        pAdapterInfo = NULL;
    }
    if (pInterfaceInfo) {
        FREE(pInterfaceInfo);
        pInterfaceInfo = NULL;
    }

    printf("----------------------\n");
    printf("This is GetIpAddrTable\n");
    printf("----------------------\n");

    pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(sizeof (MIB_IPADDRTABLE));
    if (pIPAddrTable == NULL) {
        printf("Error allocating memory needed to call GetIpAddrTable\n");
        return 1;
    }
    dwSize = 0;
    IPAddr.S_un.S_addr = ntohl(pIPAddrTable->table[1].dwAddr);	
	ip_str = InetNtopA(AF_INET, (PVOID)&IPAddr, addr, 16);

    if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
        FREE(pIPAddrTable);
        pIPAddrTable = (MIB_IPADDRTABLE *) MALLOC(dwSize);
        if (pIPAddrTable == NULL) {
            printf("Error allocating memory needed to call GetIpAddrTable\n");
            return 1;
        }
    }

    if ((dwRetVal = GetIpAddrTable(pIPAddrTable, &dwSize, 0)) != NO_ERROR) {
        printf("GetIpAddrTable failed with error %d\n", dwRetVal);
        if (pIPAddrTable)
            FREE(pIPAddrTable);
        return 1;
    }

    printf("\tNum Entries: %ld\n", pIPAddrTable->dwNumEntries);
    for (i = 0; i < (unsigned int) pIPAddrTable->dwNumEntries; i++) {
        printf("\n\tInterface Index[%d]:\t%ld\n", i,
               pIPAddrTable->table[i].dwIndex);
        IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwAddr;
		printf("\tIP Address[%d]:     \t%s\n", i, InetNtopA(AF_INET, (PVOID)&IPAddr, addr, 16));
        IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwMask;
		printf("\tSubnet Mask[%d]:    \t%s\n", i, InetNtopA(AF_INET, (PVOID)&IPAddr, addr, 16));
        IPAddr.S_un.S_addr = (u_long) pIPAddrTable->table[i].dwBCastAddr;
		printf("\tBroadCast[%d]:      \t%s (%ld)\n", i, InetNtopA(AF_INET, (PVOID)&IPAddr, addr, 16), pIPAddrTable->table[i].dwBCastAddr);
        printf("\tReassembly size[%d]:\t%ld\n", i, pIPAddrTable->table[i].dwReasmSize);
        printf("\tAddress Index[%d]:  \t%ld\n", i, pIPAddrTable->table[i].dwIndex);
        printf("\tType and State[%d]:", i);
        if (pIPAddrTable->table[i].wType & MIB_IPADDR_PRIMARY)
            printf("\tPrimary IP Address");
        if (pIPAddrTable->table[i].wType & MIB_IPADDR_DYNAMIC)
            printf("\tDynamic IP Address");
        if (pIPAddrTable->table[i].wType & MIB_IPADDR_DISCONNECTED)
            printf("\tAddress is on disconnected interface");
        if (pIPAddrTable->table[i].wType & MIB_IPADDR_DELETED)
            printf("\tAddress is being deleted");
        if (pIPAddrTable->table[i].wType & MIB_IPADDR_TRANSIENT)
            printf("\tTransient address");
        printf("\n");
    }

    //iaIPAddress = inet_addr("192.168.0.27");
    //imIPMask = inet_addr("255.255.255.0");

    //NTEContext = 0;
    //NTEInstance = 0;

    //if ((dwRetVal = AddIPAddress(iaIPAddress,
    //                             imIPMask,
    //                             pIPAddrTable->table[0].
    //                             dwIndex,
    //                             &NTEContext, &NTEInstance)) != NO_ERROR) {

    //    LPVOID lpMsgBuf;
    //    printf("\tError adding IP address.\n");

    //    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),       // Default language
    //                      (LPTSTR) & lpMsgBuf, 0, NULL)) {
    //        printf("\tError: %s", (char*)lpMsgBuf);
    //    }
    //    LocalFree(lpMsgBuf);
    //}

    //if ((dwRetVal = DeleteIPAddress(NTEContext)) != NO_ERROR) {
    //    printf("DeleteIPAddress failed with error %d\n", dwRetVal);
    //}

    /* Free allocated memory no longer needed */
    if (pIPAddrTable) {
        FREE(pIPAddrTable);
        pIPAddrTable = NULL;
    }

    printf("-------------------------\n");
    printf("This is GetIPStatistics()\n");
    printf("-------------------------\n");

    pStats = (MIB_IPSTATS *) MALLOC(sizeof (MIB_IPSTATS));
    if (pStats == NULL) {
        printf("Error allocating memory needed to call GetIpStatistics\n");
        return 1;
    }

    if ((dwRetVal = GetIpStatistics(pStats)) != NO_ERROR) {
        printf("GetIPStatistics failed with error %d\n", dwRetVal);
        if (pStats)
            FREE(pStats);
        return 1;
    }

    printf("\tNumber of IP addresses: %ld\n", pStats->dwNumAddr);
    printf("\tNumber of Interfaces: %ld\n", pStats->dwNumIf);
    printf("\tReceives: %ld\n", pStats->dwInReceives);
    printf("\tOut Requests: %ld\n", pStats->dwOutRequests);
    printf("\tRoutes: %ld\n", pStats->dwNumRoutes);
    printf("\tTimeout Time: %ld\n", pStats->dwReasmTimeout);
    printf("\tIn Delivers: %ld\n", pStats->dwInDelivers);
    printf("\tIn Discards: %ld\n", pStats->dwInDiscards);
    printf("\tTotal In: %ld\n", pStats->dwInDelivers + pStats->dwInDiscards);
    printf("\tIn Header Errors: %ld\n", pStats->dwInHdrErrors);

    /* Free allocated memory no longer needed */
    if (pStats) {
        FREE(pStats);
        pStats = NULL;
    }

    printf("-------------------------\n");
    printf("This is GetTCPStatistics()\n");
    printf("-------------------------\n");

    pTCPStats = (MIB_TCPSTATS *) MALLOC(sizeof (MIB_TCPSTATS));
    if (pTCPStats == NULL) {
        printf("Error allocating memory needed to call GetTcpStatistics\n");
        return 1;
    }

    if ((dwRetVal = GetTcpStatistics(pTCPStats)) != NO_ERROR) {
        printf("GetTcpStatistics failed with error %d\n", dwRetVal);
        if (pTCPStats)
            FREE(pTCPStats);
        return 1;
    }

    printf("\tActive Opens: %ld\n", pTCPStats->dwActiveOpens);
    printf("\tPassive Opens: %ld\n", pTCPStats->dwPassiveOpens);
    printf("\tSegments Recv: %ld\n", pTCPStats->dwInSegs);
    printf("\tSegments Xmit: %ld\n", pTCPStats->dwOutSegs);
    printf("\tTotal # Conxs: %ld\n", pTCPStats->dwNumConns);

    /* Free allocated memory no longer needed */
    if (pTCPStats) {
        FREE(pTCPStats);
        pTCPStats = NULL;
    }

    return 0;
}
示例#14
0
文件: ipconfig.c 项目: mikekap/wine
static void print_full_information(void)
{
    static const WCHAR newlineW[] = {'\n',0};
    static const WCHAR emptyW[] = {0};

    FIXED_INFO *info;
    IP_ADAPTER_ADDRESSES *adapters;
    ULONG out = 0;

    if (GetNetworkParams(NULL, &out) == ERROR_BUFFER_OVERFLOW)
    {
        info = HeapAlloc(GetProcessHeap(), 0, out);
        if (!info)
            exit(1);

        if (GetNetworkParams(info, &out) == ERROR_SUCCESS)
        {
            WCHAR hostnameW[MAX_HOSTNAME_LEN + 4];

            MultiByteToWideChar(CP_ACP, 0, info->HostName, -1, hostnameW, sizeof(hostnameW)/sizeof(hostnameW[0]));
            print_field(STRING_HOSTNAME, hostnameW);

            /* FIXME: Output primary DNS suffix. */

            print_field(STRING_NODE_TYPE, nodetype_to_string(info->NodeType));
            print_field(STRING_IP_ROUTING, boolean_to_string(info->EnableRouting));

            /* FIXME: Output WINS proxy status and DNS suffix search list. */

            ipconfig_printfW(newlineW);
        }

        HeapFree(GetProcessHeap(), 0, info);
    }

    if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_ALL_GATEWAYS,
                             NULL, NULL, &out) == ERROR_BUFFER_OVERFLOW)
    {
        adapters = HeapAlloc(GetProcessHeap(), 0, out);
        if (!adapters)
            exit(1);

        if (GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_ALL_GATEWAYS,
                                 NULL, adapters, &out) == ERROR_SUCCESS)
        {
            IP_ADAPTER_ADDRESSES *p;

            for (p = adapters; p; p = p->Next)
            {
                IP_ADAPTER_UNICAST_ADDRESS *addr;
                WCHAR physaddr_buf[3 * MAX_ADAPTER_ADDRESS_LENGTH];
                IP_ADAPTER_GATEWAY_ADDRESS_LH *gateway;
                WCHAR addr_buf[54];

                ipconfig_message_printfW(STRING_ADAPTER_FRIENDLY, iftype_to_string(p->IfType), p->FriendlyName);
                ipconfig_printfW(newlineW);
                print_field(STRING_CONN_DNS_SUFFIX, p->DnsSuffix);
                print_field(STRING_DESCRIPTION, p->Description);
                print_field(STRING_PHYS_ADDR, physaddr_to_string(physaddr_buf, p->PhysicalAddress, p->PhysicalAddressLength));
                print_field(STRING_DHCP_ENABLED, boolean_to_string(p->Flags & IP_ADAPTER_DHCP_ENABLED));

                /* FIXME: Output autoconfiguration status. */

                for (addr = p->FirstUnicastAddress; addr; addr = addr->Next)
                {
                    if (socket_address_to_string(addr_buf, sizeof(addr_buf)/sizeof(WCHAR), &addr->Address))
                        print_field(STRING_IP_ADDRESS, addr_buf);
                    /* FIXME: Output corresponding subnet mask. */
                }

                if (p->FirstGatewayAddress)
                {
                    if (socket_address_to_string(addr_buf, sizeof(addr_buf)/sizeof(WCHAR), &p->FirstGatewayAddress->Address))
                        print_field(STRING_DEFAULT_GATEWAY, addr_buf);

                    for (gateway = p->FirstGatewayAddress->Next; gateway; gateway = gateway->Next)
                    {
                        if (socket_address_to_string(addr_buf, sizeof(addr_buf)/sizeof(WCHAR), &gateway->Address))
                            print_value(addr_buf);
                    }
                }
                else
                    print_field(STRING_DEFAULT_GATEWAY, emptyW);

                ipconfig_printfW(newlineW);
            }
        }

        HeapFree(GetProcessHeap(), 0, adapters);
    }
}
示例#15
0
int adns_init(adns_state *ads_r, adns_initflags flags, FILE *diagfile) {
  adns_state ads;
  const char *res_options, *adns_res_options;
  int r;
#ifdef ADNS_JGAA_WIN32
  #define SECURE_PATH_LEN (MAX_PATH - 64)
  char PathBuf[MAX_PATH];
  struct in_addr addr;
  #define ADNS_PFIXED_INFO_BLEN (2048)
  PFIXED_INFO network_info = (PFIXED_INFO)alloca(ADNS_PFIXED_INFO_BLEN);
  ULONG network_info_blen = ADNS_PFIXED_INFO_BLEN;
  DWORD network_info_result;
  PIP_ADDR_STRING pip;
  const char *network_err_str = "";
#endif
  
  r= init_begin(&ads, flags, diagfile ? diagfile : stderr);
  if (r) return r;
  
  res_options= instrum_getenv(ads,"RES_OPTIONS");
  adns_res_options= instrum_getenv(ads,"ADNS_RES_OPTIONS");
  ccf_options(ads,"RES_OPTIONS",-1,res_options);
  ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);

#ifdef ADNS_JGAA_WIN32
  GetWindowsDirectory(PathBuf, SECURE_PATH_LEN);
  strcat(PathBuf,"\\resolv.conf");
  readconfig(ads,PathBuf,1);
  GetWindowsDirectory(PathBuf, SECURE_PATH_LEN);
  strcat(PathBuf,"\\resolv-adns.conf");
  readconfig(ads,PathBuf,0);
  GetWindowsDirectory(PathBuf, SECURE_PATH_LEN);
  strcat(PathBuf,"\\System32\\Drivers\\etc\\resolv.conf");
  readconfig(ads,PathBuf,1);
  GetWindowsDirectory(PathBuf, SECURE_PATH_LEN);
  strcat(PathBuf,"\\System32\\Drivers\\etc\\resolv-adns.conf");
  readconfig(ads,PathBuf,0);
  network_info_result = GetNetworkParams(network_info, &network_info_blen);
  if (network_info_result != ERROR_SUCCESS){
    switch(network_info_result) {
    case ERROR_BUFFER_OVERFLOW: network_err_str = "ERROR_BUFFER_OVERFLOW"; break;
    case ERROR_INVALID_PARAMETER: network_err_str = "ERROR_INVALID_PARAMETER"; break;
    case ERROR_NO_DATA: network_err_str = "ERROR_NO_DATA"; break;
    case ERROR_NOT_SUPPORTED: network_err_str = "ERROR_NOT_SUPPORTED"; break;}
    adns__diag(ads,-1,0,"GetNetworkParams() failed with error [%d] %s",
      network_info_result,network_err_str);
    }
  else {
    for(pip = &(network_info->DnsServerList); pip; pip = pip->Next) {
      addr.s_addr = inet_addr(pip->IpAddress.String);
      if ((addr.s_addr != INADDR_ANY) && (addr.s_addr != INADDR_NONE))
        addserver(ads, addr); 
    }
  }
#else
  readconfig(ads,"/etc/resolv.conf",1);
  readconfig(ads,"/etc/resolv-adns.conf",0);
#endif

  readconfigenv(ads,"RES_CONF");
  readconfigenv(ads,"ADNS_RES_CONF");

  readconfigenvtext(ads,"RES_CONF_TEXT");
  readconfigenvtext(ads,"ADNS_RES_CONF_TEXT");

  ccf_options(ads,"RES_OPTIONS",-1,res_options);
  ccf_options(ads,"ADNS_RES_OPTIONS",-1,adns_res_options);

  ccf_search(ads,"LOCALDOMAIN",-1,instrum_getenv(ads,"LOCALDOMAIN"));
  ccf_search(ads,"ADNS_LOCALDOMAIN",-1,instrum_getenv(ads,"ADNS_LOCALDOMAIN"));

  if (ads->configerrno && ads->configerrno != EINVAL) {
    r= ads->configerrno;
    init_abort(ads);
    return r;
  }

  r= init_finish(ads);
  if (r) return r;

  adns__consistency(ads,0,cc_entex);
  *ads_r= ads;
  return 0;
}
示例#16
0
lwres_result_t
lwres_conf_parse(lwres_context_t *ctx, const char *filename) {
	lwres_result_t ret;
	lwres_conf_t *confdata;
	FIXED_INFO * FixedInfo;
	ULONG    BufLen = sizeof(FIXED_INFO);
	DWORD    dwRetVal;
	IP_ADDR_STRING *pIPAddr;

	REQUIRE(ctx != NULL);
	confdata = &ctx->confdata;
	REQUIRE(confdata != NULL);

	/* Use the resolver if there is one */
	ret = generic_lwres_conf_parse(ctx, filename);
	if ((ret != LWRES_R_NOTFOUND && ret != LWRES_R_SUCCESS) ||
		(ret == LWRES_R_SUCCESS && confdata->nsnext > 0))
		return (ret);

	/*
	 * We didn't get any nameservers so we need to do this ourselves
	 */
	FixedInfo = (FIXED_INFO *) GlobalAlloc(GPTR, BufLen);
	dwRetVal = GetNetworkParams(FixedInfo, &BufLen);
	if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
		GlobalFree(FixedInfo);
		FixedInfo = GlobalAlloc(GPTR, BufLen);
		dwRetVal = GetNetworkParams(FixedInfo, &BufLen);
	}
	if (dwRetVal != ERROR_SUCCESS) {
		GlobalFree(FixedInfo);
		return (LWRES_R_FAILURE);
	}

	/* Get the search list from the registry */
	get_win32_searchlist(ctx);

	/* Use only if there is no search list */
	if (confdata->searchnxt == 0 && strlen(FixedInfo->DomainName) > 0) {
		confdata->domainname = lwres_strdup(ctx, FixedInfo->DomainName);
		if (confdata->domainname == NULL) {
			GlobalFree(FixedInfo);
			return (LWRES_R_FAILURE);
		}
	} else
		confdata->domainname = NULL;

	/* Get the list of nameservers */
	pIPAddr = &FixedInfo->DnsServerList;
	while (pIPAddr) {
		if (confdata->nsnext >= LWRES_CONFMAXNAMESERVERS)
			break;

		ret = lwres_create_addr(pIPAddr->IpAddress.String,
				&confdata->nameservers[confdata->nsnext++], 1);
		if (ret != LWRES_R_SUCCESS) {
			GlobalFree(FixedInfo);
			return (ret);
		}
		pIPAddr = pIPAddr ->Next;
	}

	GlobalFree(FixedInfo);
	return (LWRES_R_SUCCESS);
}
void PcapLiveDeviceList::setDnsServers()
{
#ifdef WIN32
	FIXED_INFO * fixedInfo;
	ULONG    ulOutBufLen;
	DWORD    dwRetVal;
	IP_ADDR_STRING * pIPAddr;

	uint8_t buf1[sizeof(FIXED_INFO)];
	fixedInfo = (FIXED_INFO *) buf1;
	ulOutBufLen = sizeof( FIXED_INFO );

	dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen );
	uint8_t buf2[ulOutBufLen];
	if(ERROR_BUFFER_OVERFLOW == dwRetVal)
	{
		fixedInfo = (FIXED_INFO *)buf2;
	}

	if ((dwRetVal = GetNetworkParams( fixedInfo, &ulOutBufLen )) != 0)
		LOG_ERROR("Call to GetNetworkParams failed. Return Value: %08lx\n", dwRetVal);
	else
	{
		m_DnsServers.push_back(IPv4Address(fixedInfo->DnsServerList.IpAddress.String));
		int i = 1;
		LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, fixedInfo->DnsServerList.IpAddress.String );

		pIPAddr = fixedInfo->DnsServerList.Next;
		while ( pIPAddr )
		{
			m_DnsServers.push_back(IPv4Address(pIPAddr->IpAddress.String));
			LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, pIPAddr->IpAddress.String);
			pIPAddr = pIPAddr -> Next;
		}
	}
#elif LINUX
	std::string command = "nmcli dev list | grep IP4.DNS";
	std::string dnsServersInfo = executeShellCommand(command);
	if (dnsServersInfo == "")
	{
		LOG_DEBUG("Error retrieving DNS server list: call to nmcli gave no output");
		return;
	}

	std::istringstream stream(dnsServersInfo);
	std::string line;
	int i = 1;
	while(std::getline(stream, line))
	{
		std::istringstream lineStream(line);
		std::string headline;
		std::string dnsIP;
		lineStream >> headline;
		lineStream >> dnsIP;
		IPv4Address dnsIPAddr(dnsIP);
		if (!dnsIPAddr.isValid())
			continue;

		if (std::find(m_DnsServers.begin(), m_DnsServers.end(), dnsIPAddr) == m_DnsServers.end())
		{
			m_DnsServers.push_back(dnsIPAddr);
			LOG_DEBUG("Default DNS server IP #%d: %s\n", i++, dnsIPAddr.toString().c_str());
		}
	}
#elif MAC_OS_X

	SCDynamicStoreRef dynRef = SCDynamicStoreCreate(kCFAllocatorSystemDefault, CFSTR("iked"), NULL, NULL);
	if (dynRef == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: failed to retrieve SCDynamicStore");
		return;
	}

	CFDictionaryRef dnsDict = (CFDictionaryRef)SCDynamicStoreCopyValue(dynRef,CFSTR("State:/Network/Global/DNS"));

	if (dnsDict == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: failed to get DNS dictionary");
		CFRelease(dynRef);
		return;
	}

	CFArrayRef serverAddresses = (CFArrayRef)CFDictionaryGetValue(dnsDict, CFSTR("ServerAddresses"));

	if (serverAddresses == NULL)
	{
		LOG_DEBUG("Couldn't set DNS server list: server addresses array is null");
		CFRelease(dynRef);
		CFRelease(dnsDict);
		return;
	}

	CFIndex count = CFArrayGetCount(serverAddresses);
	for (CFIndex i = 0; i < count; i++)
	{
		CFStringRef serverAddress = (CFStringRef)CFArrayGetValueAtIndex(serverAddresses, i);

		if (serverAddress == NULL)
			continue;

		uint8_t buf[20];
		char* serverAddressCString = (char*)buf;
		CFStringGetCString(serverAddress, serverAddressCString, 20, kCFStringEncodingUTF8);
		m_DnsServers.push_back(IPv4Address(serverAddressCString));
		LOG_DEBUG("Default DNS server IP #%d: %s\n", (int)(i+1), serverAddressCString);
	}

	CFRelease(dynRef);
	CFRelease(dnsDict);
#endif
}
示例#18
0
/***********************************************************************
 *
 get_dns_info: Get the search list or the domain name
	       and the dns server addresses in Network Byte Order
	       Set statp->os_query if DnsQuery is available.

***********************************************************************/
void get_dns_info(res_state statp)
{
#if MAX_HOSTNAME_LEN > MAXHOSTNAMELEN
#define MAX_HOSTNAME_SIZE (MAX_HOSTNAME_LEN + 1)
#else
#define MAX_HOSTNAME_SIZE (MAXHOSTNAMELEN + 1)
#endif
#if MAX_HOSTNAME_SIZE > 256 /* sizeof(defdname) */
#error stap->defdname too short
#endif

  int res, debug = statp->options & RES_DEBUG;

  ULONG ulOutBufLen = 0;
  DWORD dwRetVal;
  IP_ADDR_STRING * pIPAddr;
  FIXED_INFO * pFixedInfo;
  int numAddresses = 0;

  if (statp->use_os
      && ((dwRetVal = DnsQuery_A(NULL, 0, 0, NULL, NULL, NULL)) != ERROR_PROC_NOT_FOUND))
  {
    DPRINTF(debug, "using dnsapi.dll %d\n", dwRetVal);
    statp->os_query = (typeof(statp->os_query)) cygwin_query;
    /* We just need the search list. Avoid loading iphlpapi. */
    statp->nscount = -1;
  }

  if (statp->nscount != 0)
    goto use_registry;

  /* First call to get the buffer length we need */
  dwRetVal = GetNetworkParams((FIXED_INFO *) 0, &ulOutBufLen);
  if (dwRetVal != ERROR_BUFFER_OVERFLOW) {
    DPRINTF(debug, "GetNetworkParams: error %lu (Windows)\n", dwRetVal);
    goto use_registry;
  }
  if ((pFixedInfo = (FIXED_INFO *) alloca(ulOutBufLen)) == 0) {
    DPRINTF(debug, "alloca: %s\n", strerror(errno));
    goto use_registry;
  }
  if ((dwRetVal = GetNetworkParams(pFixedInfo, & ulOutBufLen))) {
    DPRINTF(debug, "GetNetworkParams: error %lu (Windows)\n", dwRetVal);
    goto use_registry;
  }

  DPRINTF(debug, "GetNetworkParams: OK\n");
  /* Record server addresses, up to array size */
  for (pIPAddr = &(pFixedInfo->DnsServerList), numAddresses = 0;
       pIPAddr;
       pIPAddr = pIPAddr->Next) {
    if (numAddresses < DIM(statp->nsaddr_list)) {
	DPRINTF(debug, "server \"%s\"\n", pIPAddr->IpAddress.String);
      statp->nsaddr_list[numAddresses].sin_addr.s_addr = cygwin_inet_addr(pIPAddr->IpAddress.String);
      if (statp->nsaddr_list[numAddresses].sin_addr.s_addr != 0) {
	numAddresses++;
	statp->nscount++;
      }
    }
    else
      DPRINTF(debug, "no space for server \"%s\"\n", pIPAddr->IpAddress.String);
  }

 use_registry:
  get_registry_dns(statp);

  if (!statp->dnsrch[0]) {
    statp->defdname[sizeof(statp->defdname) - 1] = 0;
    if (!(res = getdomainname(statp->defdname, sizeof(statp->defdname)))) {
      if (statp->defdname[0] && !statp->defdname[sizeof(statp->defdname) - 1])
	statp->dnsrch[0] = statp->defdname;
    }
    DPRINTF(debug, "getdomainname \"%s\"\n",
	    (res)? strerror(errno) : statp->defdname);
  }
}
示例#19
0
void OnInitNetDetailsDialog(HWND hwndDlg)
{
    PIP_ADAPTER_INFO    pAdapterInfo = NULL, pAdapterInfoHead = NULL;
    PFIXED_INFO         pNetworkParams = NULL;
    PIP_ADDR_STRING pDnsServer = NULL;
    ULONG               ulBufferSize = 0;
    DWORD               dwRetVal;
    HRESULT             hr = S_OK;
    DWORD               i;
    WCHAR               szIpAddr[MAX_IP_FIELD_WIDTH];
    WCHAR               szGateway[MAX_IP_FIELD_WIDTH];
    WCHAR               szSubnetMsk[MAX_IP_FIELD_WIDTH];
    WCHAR               szDHCPServer[MAX_IP_FIELD_WIDTH];
    WCHAR               szPhysicalAddr[MAX_WZCPHYSADDR_STR];
    WCHAR               szLeaseObtained[MAX_WZCIPCFGMISC_STR];
    WCHAR               szLeaseExpires[MAX_WZCIPCFGMISC_STR];
    WCHAR               szDNS1[MAX_IP_FIELD_WIDTH];
    WCHAR               szDNS2[MAX_IP_FIELD_WIDTH];
    WCHAR               szWINS1[MAX_IP_FIELD_WIDTH];
    WCHAR               szWINS2[MAX_IP_FIELD_WIDTH];
    WCHAR*				pTime;
    FILETIME            LeaseObtained, LeaseObtainedLocal;
    SYSTEMTIME          SysLeaseObtained;
    FILETIME            LeaseExpires, LeaseExpiresLocal;
    SYSTEMTIME          SysLeaseExpires;
    LV_COLUMN           lvCol = {0};
    RECT                rect;
    int                 iParamColWidth = 0; 
    TCHAR               szProperty[MAX_WZCIPCFGMISC_STR];
    int                 iIndex = 0;
    HWND                hList = GetDlgItem(hwndDlg, IDC_LIST_IPCFG);

    // Get IP adapter info
    hr = GetIPAdapterInfo(hwndDlg, &pAdapterInfoHead, &pAdapterInfo);
    if (FAILED(hr)) {
        DEBUGMSG(ZONE_ERROR, (TEXT("NETUIQC: Could not get the adapter info")));
        goto exit;
    }

    // Get IP data from iphelper

    wsprintf(szPhysicalAddr, TEXT("%02X"), pAdapterInfo->Address[0]);
    for (i=1;i<pAdapterInfo->AddressLength;i++) {
        wsprintf(szPhysicalAddr, TEXT("%s %02X"), szPhysicalAddr, pAdapterInfo->Address[i]);
    }

    mbstowcs(szIpAddr, pAdapterInfo->IpAddressList.IpAddress.String, strlen(pAdapterInfo->IpAddressList.IpAddress.String)+1);
    mbstowcs(szGateway, pAdapterInfo->GatewayList.IpAddress.String, strlen(pAdapterInfo->GatewayList.IpAddress.String)+1);
    mbstowcs(szSubnetMsk, pAdapterInfo->IpAddressList.IpMask.String, strlen(pAdapterInfo->IpAddressList.IpMask.String)+1);  
    mbstowcs(szDHCPServer, pAdapterInfo->DhcpServer.IpAddress.String, strlen(pAdapterInfo->DhcpServer.IpAddress.String)+1);
    mbstowcs(szWINS1, pAdapterInfo->PrimaryWinsServer.IpAddress.String, strlen(pAdapterInfo->PrimaryWinsServer.IpAddress.String)+1);
    mbstowcs(szWINS2, pAdapterInfo->SecondaryWinsServer.IpAddress.String, strlen(pAdapterInfo->SecondaryWinsServer.IpAddress.String)+1);

	// Get system time for lease obtained
    TimeToFileTime(pAdapterInfo->LeaseObtained, &LeaseObtained);
    FileTimeToLocalFileTime(&LeaseObtained, &LeaseObtainedLocal);    
    FileTimeToSystemTime(&LeaseObtainedLocal, &SysLeaseObtained);

	// Format string for lease obtained
    GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &SysLeaseObtained, NULL, szLeaseObtained, MAX_WZCIPCFGMISC_STR);
	wcscat(szLeaseObtained, TEXT(" "));
	pTime = szLeaseObtained + wcslen(szLeaseObtained); // Advance pointer to append time
	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOTIMEMARKER, &SysLeaseObtained, NULL, pTime, (MAX_WZCIPCFGMISC_STR - wcslen(pTime)));

	// Get system time for lease expiry
    TimeToFileTime(pAdapterInfo->LeaseExpires, &LeaseExpires);
    FileTimeToLocalFileTime(&LeaseExpires, &LeaseExpiresLocal);    
    FileTimeToSystemTime(&LeaseExpiresLocal, &SysLeaseExpires);

	// Format string for lease expiry
    GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, &SysLeaseExpires, NULL, szLeaseExpires, MAX_WZCIPCFGMISC_STR);
	wcscat(szLeaseExpires, TEXT(" "));
	pTime = szLeaseExpires + wcslen(szLeaseExpires); // Advance pointer to append time
	GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOTIMEMARKER, &SysLeaseExpires, NULL, pTime, (MAX_WZCIPCFGMISC_STR - wcslen(pTime)));

    // Get Network params struct for DNS servers
    dwRetVal = GetNetworkParams(pNetworkParams, &ulBufferSize);
    if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
        pNetworkParams = (PFIXED_INFO)malloc(ulBufferSize);
        if (pNetworkParams == NULL) {
            DEBUGMSG(ZONE_ERROR, (TEXT("NETUIQC: Could not allocate memory for network params")));
            goto exit;
        }

        dwRetVal = GetNetworkParams(pNetworkParams, &ulBufferSize);
        if (dwRetVal != ERROR_SUCCESS) {
            DEBUGMSG(ZONE_ERROR, (TEXT("NETUIQC: Could not get network params")));
            goto exit;
        }
    } else if (dwRetVal != ERROR_SUCCESS) {
        DEBUGMSG(ZONE_ERROR, (TEXT("NETUIQC: Could not get network params")));
        goto exit;
    }

    if (pNetworkParams == NULL) {
        DEBUGMSG(ZONE_ERROR, (TEXT("NETUIQC: Could not get network params")));
        goto exit;
    }

    // Get DNS Servers
    pDnsServer = &(pNetworkParams->DnsServerList);
    mbstowcs(szDNS1, pDnsServer->IpAddress.String, strlen(pDnsServer->IpAddress.String)+1);
    pDnsServer = pDnsServer->Next;
    if (pDnsServer != NULL) {
        mbstowcs(szDNS2, pDnsServer->IpAddress.String, strlen(pDnsServer->IpAddress.String)+1); 
    } else {
        szDNS2[0] = 0;
    }

    // Update UI
    mbstowcs(szProperty,pAdapterInfo->AdapterName,strlen(pAdapterInfo->AdapterName)+1);
    SetWindowText(hwndDlg,szProperty);

    GetClientRect(hList, &rect);
    iParamColWidth = (rect.right/2);
    
    lvCol.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT ;
    lvCol.fmt = LVCFMT_LEFT;   // left-align column
    lvCol.cx = iParamColWidth;

    if (LoadString(v_hInst, IDS_IPCFG_PRAMETER,szProperty,sizeof(szProperty)/sizeof(szProperty[0]))) {
        lvCol.pszText = szProperty;
        iIndex = ListView_InsertColumn(hList, iIndex, &lvCol);
        iIndex++;
    }

    if (LoadString(v_hInst, IDS_IPCFG_VALUE,szProperty,sizeof(szProperty)/sizeof(szProperty[0]))) {
        lvCol.cx      = rect.right - iParamColWidth;
        lvCol.pszText = szProperty;
        iIndex = ListView_InsertColumn(hList, iIndex, &lvCol);
    }

    ListView_SetExtendedListViewStyle(hList, LVS_EX_FULLROWSELECT);

    iIndex=0;
    if (LoadString(v_hInst,IDS_IPCFG_PH_ADDR,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szPhysicalAddr);
    if (LoadString(v_hInst,IDS_IPCFG_IPADDR,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szIpAddr);
    if (LoadString(v_hInst,IDS_IPCFG_SUBNET,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szSubnetMsk);
    if (LoadString(v_hInst,IDS_IPCFG_DEFGW,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szGateway);
    if (LoadString(v_hInst,IDS_IPCFG_DHCP,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szDHCPServer);
    if (LoadString(v_hInst,IDS_IPCFG_LEASE_OBT,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szLeaseObtained);
    if (LoadString(v_hInst,IDS_IPCFG_LEASE_EXP,szProperty,sizeof(szProperty)/sizeof(szProperty[0])))
        AddToListControl(hList, iIndex++, szProperty, szLeaseExpires);
    if (LoadString(v_hInst,IDS_IPCFG_DNSSERVERS,szProperty,sizeof(szProperty)/sizeof(szProperty[0]))) {
        AddToListControl(hList, iIndex++, szProperty, szDNS1);
        AddToListControl(hList, iIndex++, L"", szDNS2);
    }
    if (LoadString(v_hInst,IDS_IPCFG_WINSSERVERS,szProperty,sizeof(szProperty)/sizeof(szProperty[0]))) {
        AddToListControl(hList, iIndex++, szProperty, szWINS1);
        AddToListControl(hList, iIndex++, L"", szWINS2);
    }

    exit:
    if (pAdapterInfoHead) {
        free(pAdapterInfoHead);
    }
    if (pNetworkParams) {
        free(pNetworkParams);
    }

    return; 

} // OnInitNetDetailsDialog
	Handle<Value> Get(const Arguments &args) {
		HandleScope scope;

		FIXED_INFO *pFixedInfo;
		ULONG ulOutBufLen;
		DWORD dwRetVal;
		IP_ADDR_STRING *pDNS;

		pFixedInfo = (FIXED_INFO *) MALLOC(sizeof (FIXED_INFO));
		if (pFixedInfo == NULL) {
			ThrowException(Exception::Error(String::New("Error allocating memory")));
			return scope.Close(Undefined());
		}
		ulOutBufLen = sizeof (FIXED_INFO);

		// Make an initial call to GetAdaptersInfo to get
		// the necessary size into the ulOutBufLen variable
		if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
			FREE(pFixedInfo);
			pFixedInfo = (FIXED_INFO *) MALLOC(ulOutBufLen);
			if (pFixedInfo == NULL) {
				ThrowException(Exception::Error(String::New("Error allocating memory")));
				return scope.Close(Undefined());
			}
		}

		
		if (dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen) == NO_ERROR) {		
			Local<Object> r = Object::New();

			r->Set(String::NewSymbol("hostName"), String::NewSymbol(pFixedInfo->HostName));
			r->Set(String::NewSymbol("domainName"), String::NewSymbol(pFixedInfo->DomainName));
			
			Local<Array> dns = Array::New();
			//dns->
			uint32_t i = 0;

			dns->Set(i++, String::NewSymbol(pFixedInfo->DnsServerList.IpAddress.String));
			pDNS = pFixedInfo->DnsServerList.Next;
			while (pDNS) {
				dns->Set(i++, String::NewSymbol(pDNS->IpAddress.String));
				pDNS = pDNS->Next;
			}
				
			r->Set(String::NewSymbol("dnsServers"), dns);
			r->Set(String::NewSymbol("dnsEnabled"), Boolean::New(pFixedInfo->EnableDns));
			r->Set(String::NewSymbol("nodeType"), Number::New(pFixedInfo->NodeType));
			r->Set(String::NewSymbol("domain"), String::NewSymbol(pFixedInfo->DomainName));
			r->Set(String::NewSymbol("arpProxyEnabled"), Boolean::New(pFixedInfo->EnableProxy));
			r->Set(String::NewSymbol("routingEnabled"), Boolean::New(pFixedInfo->EnableRouting));
			r->Set(String::NewSymbol("dhcpScope"), String::NewSymbol(pFixedInfo->ScopeId));


			if (pFixedInfo) FREE(pFixedInfo);
			return scope.Close(r);

		} else {
			if (pFixedInfo) FREE(pFixedInfo);
			ThrowException(Exception::TypeError(String::New("GetNetworkParams failed with error " + dwRetVal)));
			return scope.Close(Undefined());
		}

		if (pFixedInfo)
			FREE(pFixedInfo);

		return scope.Close(Undefined());

	}