Ejemplo n.º 1
0
int main() {
  HMODULE hNsi = LoadLibraryW(L"Nsi.dll");
  NsiGetParameterProc _NsiGetParameter = (NsiGetParameterProc)GetProcAddress(hNsi, "NsiGetParameter");

  // Declare and initialize variables
  PIP_INTERFACE_INFO pInfo = NULL;
  ULONG ulOutBufLen = 0;

  DWORD dwRetVal = 0;
  int iReturn = 1;

  int i;

  // Make an initial call to GetInterfaceInfo to get
  // the necessary size in the ulOutBufLen variable
  dwRetVal = GetInterfaceInfo(NULL, &ulOutBufLen);
  if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) {
    pInfo = (IP_INTERFACE_INFO *)MALLOC(ulOutBufLen);
    if (pInfo == NULL) {
      printf
        ("Unable to allocate memory needed to call GetInterfaceInfo\n");
      return 1;
    }
  }
  // Make a second call to GetInterfaceInfo to get
  // the actual data we need
  dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen);
  if (dwRetVal == NO_ERROR) {
    printf("Number of Adapters: %ld\n\n", pInfo->NumAdapters);
    for (i = 0; i < pInfo->NumAdapters; i++) {
      printf("Adapter Index[%d]: %ld\n", i,
        pInfo->Adapter[i].Index);

      NET_LUID Luid;
      NETIO_STATUS st = ConvertInterfaceIndexToLuid(pInfo->Adapter[i].Index, &Luid);
      if (st == NO_ERROR) {
        BYTE OutputBuffer[0xB8] = { /* zero padding */ };
        DWORD nsi_st = _NsiGetParameter(1, NPI_MS_IPV4_MODULEID, 7, &Luid, sizeof(Luid), 0, OutputBuffer, sizeof(OutputBuffer), 0);
        if (nsi_st == NO_ERROR) {
          PrintHex(OutputBuffer, sizeof(OutputBuffer));
        }
      }
    }
    iReturn = 0;
  }
  else if (dwRetVal == ERROR_NO_DATA) {
    printf
      ("There are no network adapters with IPv4 enabled on the local system\n");
    iReturn = 0;
  }
  else {
    printf("GetInterfaceInfo failed with error: %d\n", dwRetVal);
    iReturn = 1;
  }

  FREE(pInfo);
  return (iReturn);
}
/*
 * DetermineAdapter
 * 
 * NOTE:
 *   
 *    This code retrieves the Adapter Name to use for the DHCP Client API 
 *    using the IPHelper API.
 *   
 *    NT has a name for the adapter that through this API has device 
 *    information in front of it followed by a {GUID}, 98 does not and 
 *    the Index is used instead. So if the string is set to ?? (what it is 
 *    in 98) we revert to using the string representation of the index.
 *     
 */
LPSTR DetermineAdapter()
{
  DWORD dwResult;                            // result of API calls
  IP_INTERFACE_INFO * pInfo = NULL;          // adapter information structure
  DWORD dwSize = 0;                          // size of required buffer
  CHAR szAdapter[MAX_ADAPTER_NAME] = {0};    // the adapter to use 
  char * ptr;                                // pointer to adapter name

  // get buffer size
  dwResult = GetInterfaceInfo(NULL, &dwSize);     
  if (dwResult == ERROR_INSUFFICIENT_BUFFER)
    {
    // allocate buffer
    pInfo = (IP_INTERFACE_INFO *) LocalAlloc(LPTR, dwSize);
    if (!pInfo)
      {
      OutputError(GetLastError());
      exit(1);
      }

    // make the actual call
    dwResult = GetInterfaceInfo(pInfo, &dwSize);
    if (dwResult != ERROR_SUCCESS)
      {
      OutputError(GetLastError());
      exit(2);
      }
    }
  else
    {
    OutputError(GetLastError());
    exit(3);
    }
  
  // convert, parse, and convert back
  ptr = NULL;
  WideCharToMultiByte(0, 0, pInfo->Adapter[0].Name, 
                            lstrlenW(pInfo->Adapter[0].Name), 
                            szAdapter, MAX_ADAPTER_NAME, NULL, NULL);
  if (szAdapter[0] != '?')
    {
    // find the GUID
    ptr = strchr(szAdapter, '{'); 
    }

  // use index if the pointer is not set
  if (!ptr)
    {
    sprintf_s(szAdapter, MAX_ADAPTER_NAME, "%ld\0", pInfo->Adapter[0].Index);            
    ptr = szAdapter;
    }

  // free what was allocated
  if (pInfo)
    LocalFree(pInfo);

  return ptr;
}
Ejemplo n.º 3
0
DWORD WINAPI CLuzj_ZTEDlg::IpconfigRenew()
{

	int i;
	DWORD ret;
	char  adaptername[MAX_ADAPTER_NAME];
	int count = 0;

	DWORD dwOutBufLen = sizeof(IP_INTERFACE_INFO);
	PIP_INTERFACE_INFO pIfTable = (PIP_INTERFACE_INFO)malloc(dwOutBufLen);
	if(pIfTable == NULL) return -1;
	
	ret = GetInterfaceInfo(pIfTable, &dwOutBufLen);
	if(ret == ERROR_INSUFFICIENT_BUFFER) {
		free(pIfTable); pIfTable = (PIP_INTERFACE_INFO)malloc(dwOutBufLen);
		if(pIfTable == NULL) return -2;
		ret = GetInterfaceInfo(pIfTable, &dwOutBufLen);
	}

	if(ret != NO_ERROR) return -3;

	for(i = 0; i < pIfTable->NumAdapters; i++) {
		wcstombs(adaptername, pIfTable->Adapter[i].Name, MAX_ADAPTER_NAME);

		if(stricmp(adaptername, ToTCPName(Config.m_csNetCard)) == 0) {

			EnableDHCP(GetGUID(adaptername), true);
			
			while(1) {
				if(count <= MAX_DHCP_TIMES) Log(I_INFO, "fetching IP address by DHCP...");	
				IpReleaseAddress(&pIfTable->Adapter[i]);
				ret = IpRenewAddress(&pIfTable->Adapter[i]);
				if(ret == NO_ERROR) break;	
				if(count <= MAX_DHCP_TIMES) {
					if(count == MAX_DHCP_TIMES) {
						count++;
						Log(I_INFO, "dhcp keep quiet.");
					} else {
						Log(I_WARN, "fetch IP address failed. (%d)", ret); count++;
					}
				} 
				Sleep(10000);
			}
			
			char *info = GetAdapterInfo((LPCSTR)Config.m_csNetCard);
			if(info == NULL) Log(I_INFO, "GetAdapterInfo: NULL");
			else Log(I_INFO, info);		

			break;
		}	
	}

	free(pIfTable);
	return 0;
}
Ejemplo n.º 4
0
/*!	\brief Changes the current interface.
	
	If this fails it will set the interface's \a ID to \c PPP_UNDEFINED_INTERFACE_ID.
	
	\param ID The ID of the new interface.
	
	\return
		- \c B_OK: Object could be initialized successfully and the interface exists.
		- \c B_BAD_INDEX: The interface does not exist.
		- any other value: The PPP stack could not be loaded.
	
	\sa Control()
*/
status_t
PPPInterface::SetTo(ppp_interface_id ID)
{
	// printf("Set To %ld begin=============================\n", ID);
	if (fFD < 0) {
		printf("No fFD\n");
		return B_ERROR;
	}

	fID = ID;
	
	ppp_interface_info_t info;
	// printf("SetTo info:%p\n", &info);
	if (GetInterfaceInfo(&info)) {
		fName = info.info.name;
		fID = ID;
		// printf("%s fine: name:%s, fID:%ld\n", __func__, info.info.name, fID);
	} else {
		fName = "";
		fID = PPP_UNDEFINED_INTERFACE_ID;
		// printf("%s fail: name:%s, fID:%ld\n", __func__, "", fID);
		return B_ERROR;
	}
	
	// printf("Set To %ld end =============================\n", ID);

	return B_OK;
}
Ejemplo n.º 5
0
int win32_list_interfaces()
{

// Declare and initialize variables
    PIP_INTERFACE_INFO pInfo = NULL;
    ULONG ulOutBufLen = 0;

    DWORD dwRetVal = 0;
    int iReturn = 1;

    int i;

// Make an initial call to GetInterfaceInfo to get
// the necessary size in the ulOutBufLen variable
    dwRetVal = GetInterfaceInfo(NULL, &ulOutBufLen);
    if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) {
        pInfo = (IP_INTERFACE_INFO *) malloc(ulOutBufLen);
        if (pInfo == NULL) {
            printf
                ("Unable to allocate memory needed to call GetInterfaceInfo\n");
            return 1;
        }
    }
// Make a second call to GetInterfaceInfo to get
// the actual data we need
    dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen);
    if (dwRetVal == NO_ERROR) {
        printf("Number of Adapters: %ld\n\n", pInfo->NumAdapters);
        for (i = 0; i < pInfo->NumAdapters; i++) {
            printf("Adapter Index[%d]: %ld\n", i,
                   pInfo->Adapter[i].Index);
            printf("Adapter Name[%d]: %ws\n\n", i,
                   pInfo->Adapter[i].Name);
        }
        iReturn = 0;
    } else if (dwRetVal == ERROR_NO_DATA) {
        printf
            ("There are no network adapters with IPv4 enabled on the local system\n");
        iReturn = 0;
    } else {
        printf("GetInterfaceInfo failed with error: %d\n", dwRetVal);
        iReturn = 1;
    }

    free(pInfo);
    return (iReturn);
}
Ejemplo n.º 6
0
/*
 * Get interface info, which contains Adapter[] that has the MIB index
 */
PIP_INTERFACE_INFO getIpInterfaceInfo(void) {

	DWORD size = 0;
	PIP_INTERFACE_INFO  info = NULL;

	// Get the require size of the structure
	if (GetInterfaceInfo(info, &size) == ERROR_INSUFFICIENT_BUFFER) {
		info = (PIP_INTERFACE_INFO) malloc(size);
	} else {
		return NULL;
	}

	// Now fill in the structure
	GetInterfaceInfo(info, &size);

	return info;
}
Ejemplo n.º 7
0
int main (int argc,char **argv)

{
CheckOpts(argc,argv);
MonInitialize();
GetNameInfo();
GetInterfaceInfo();
GetV6InterfaceInfo();  
StartServer(argc,argv);
return 0;
}
Ejemplo n.º 8
0
void CConfigControl::InitializeConnectionL(
	const TConnectionInfo& aInfo)
/**
 * Sets up the ESOCK connection, retrieves the interface name and the hardware address.
 *
 * @internalComponent
 * 
 * @leave System errors - if any of the called methods leaves.
 */
	{	
	__FLOG_STATIC(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Start"));				

	TInt rc = iEsock.Connect();
	if (KErrNone != rc)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to connect to the ESOCK server [%d]"), rc);				
		User::Leave(rc);				
		}
	
	rc = iConnection.Open(iEsock);
	if (KErrNone != rc)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to open connection [%d]"), rc);				
		User::Leave(rc);				
		}
	
	// start the connection, this will bring up everything
	TConnectionInfoBuf infoBuf = aInfo;
	
	// Attach as Monitor - we need access to the interface for control purposes only, and don't want to affect Nifman idle timers. 
	// If we attach with EAttachTypeNormal, we prevent Nifman from ever switching to Short (Last Session Closed) Idle Timer.
	rc = iConnection.Attach(infoBuf,RConnection::EAttachTypeMonitor);
	if (KErrNone != rc)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to start connection [%d]"), rc);				
		User::Leave(rc);				
		}
		
	rc = iSocket.Open(iEsock, KAfInet, KSockDatagram, KProtocolInetUdp, iConnection);
	if (rc != KErrNone)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to open socket [%d]"), rc);
		User::Leave(rc);
		}
		
	// retrieve the connection information		
	rc = GetInterfaceName(aInfo, iInterfaceName);
	if (KErrNone != rc)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to get the interface name [%d]"), rc);				
		User::Leave(rc);
		}
		
	TSoInetInterfaceInfo info;
	rc = GetInterfaceInfo(iInterfaceName, info);
	if (KErrNone != rc)
		{
		__FLOG_STATIC1(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - Failed to get the interface info [%d]"), rc);				
		User::Leave(rc);
		}
	
	iHardwareAddr = info.iHwAddr;
		
	__FLOG_STATIC(KConfigLoggingTag1(), KConfigLoggingTag2(), _L("CConfigControl::InitializeConnectionL - End"));				
	}
Ejemplo n.º 9
0
Archivo: win.c Proyecto: hermixy/qtun
size_t enum_devices(enum_device_t devices[MAX_DEVICE_COUNT])
{
    ULONG len = 0;
    IP_ADAPTER_INFO* adapters = NULL;
    IP_INTERFACE_INFO* interfaces = NULL;
    HANDLE handle = INVALID_HANDLE_VALUE;
    size_t idx = 0;

    if (GetAdaptersInfo(NULL, &len) == ERROR_NO_DATA) goto failed;

    adapters = malloc(sizeof(IP_ADAPTER_INFO) * len);
    if (adapters == NULL) goto failed;

    if (GetAdaptersInfo(adapters, &len) == ERROR_SUCCESS)
    {
        IP_ADAPTER_INFO* adp = adapters;
        while (adp)
        {
            if (adp->Type == MIB_IF_TYPE_ETHERNET)
            {
                if (strncmp(adp->Description, "QTun", sizeof("QTun") - 1) == 0)
                {
                    devices[idx].index = adp->Index;
                    strcpy(devices[idx].dev_path, "\\\\.\\");
                    strcat(devices[idx].dev_path, adp->AdapterName);
                    strcat(devices[idx].dev_path, ".tun");
                    ++idx;
                }
            }
            adp = adp->Next;
        }
    }

    MprConfigServerConnect(NULL, &handle);

    len = 0;
    if (GetInterfaceInfo(NULL, &len) == ERROR_NO_DATA) goto failed;

    interfaces = malloc(sizeof(IP_INTERFACE_INFO) * len);
    if (interfaces == NULL) goto failed;

    if (GetInterfaceInfo(interfaces, &len) == ERROR_SUCCESS)
    {
        LONG i;
        size_t j;
        for (i = 0; i < interfaces->NumAdapters; ++i)
        {
            for (j = 0; j < idx; ++j)
            {
                if (devices[j].index == interfaces->Adapter[i].Index)
                {
                    WCHAR w_name[128] = { 0 };
                    int name_len = 0;
                    MprConfigGetFriendlyName(handle, interfaces->Adapter[i].Name, w_name, sizeof(w_name));
                    name_len = WideCharToMultiByte(CP_ACP, 0, w_name, -1, NULL, 0, NULL, FALSE);
                    WideCharToMultiByte(CP_ACP, 0, w_name, -1, devices[j].dev_name, name_len, NULL, FALSE);
                    break;
                }
            }
        }
    }

    if (adapters) free(adapters);
    if (interfaces) free(interfaces);
    return idx;
failed:
    if (adapters) free(adapters);
    if (interfaces) free(interfaces);
    return 0;
}
Ejemplo n.º 10
0
static
VOID
test_GetInterfaceName(VOID)
{
    PIP_INTERFACE_INFO pInfo = NULL;
    ULONG ulOutBufLen = 0;
    DWORD ApiReturn;
    WCHAR Name[MAX_ADAPTER_NAME];
    UNICODE_STRING GuidString;
    GUID AdapterGUID;
    HINSTANCE hIpHlpApi;

    ApiReturn = GetInterfaceInfo(pInfo, &ulOutBufLen);
    ok(ApiReturn == ERROR_INSUFFICIENT_BUFFER,
       "GetInterfaceInfo(pInfo, &ulOutBufLen) returned %ld, expected ERROR_INSUFFICIENT_BUFFER\n",
       ApiReturn);
    if (ApiReturn != ERROR_INSUFFICIENT_BUFFER)
    {
        skip("Can't determine size of IP_INTERFACE_INFO. Can't proceed\n");
        return;
    }

    pInfo = (IP_INTERFACE_INFO *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ulOutBufLen);
    if (pInfo == NULL)
    {
        skip("pInfo is NULL. Can't proceed\n");
        return;
    }

    ApiReturn = GetInterfaceInfo(pInfo, &ulOutBufLen);
    ok(ApiReturn == NO_ERROR,
        "GetInterfaceInfo(pInfo, &ulOutBufLen) returned %ld, expected NO_ERROR\n",
        ApiReturn);
    if (ApiReturn != NO_ERROR || ulOutBufLen == 0)
    {
        skip("GetInterfaceInfo failed with error %ld. Can't proceed\n", ApiReturn);
        return;
    }

    if (pInfo->NumAdapters > 0)
        CopyMemory(&Name, &pInfo->Adapter[0].Name, sizeof(Name));

    if (pInfo->NumAdapters == 0)
    {
        HeapFree(GetProcessHeap(), 0, pInfo);
        skip("pInfo->NumAdapters = 0. Can't proceed\n");
        return;
    }
    trace("pInfo->NumAdapters: %lu\n", pInfo->NumAdapters);

    HeapFree(GetProcessHeap(), 0, pInfo);

    ApiReturn = wcsncmp(Name, L"\\DEVICE\\TCPIP_", 14);
    ok(ApiReturn == 0,
       "wcsncmp(Name, L\"\\DEVICE\\TCPIP_\", 14) returned %ld, expected 0\n",
       ApiReturn);
    if (ApiReturn != 0)
    {
        if (wcslen(Name) == 0)
        {
            skip("pInfo->Adapter[0].Name is empty. Can't proceed\n");
            return;
        }
        else
        {
            // workaround for ReactOS
            trace("pInfo->Adapter[0].Name = \"%ls\" is incorrect.\n", Name);
            RtlInitUnicodeString(&GuidString, &Name[0]);
        }
    }
    else
    {
        RtlInitUnicodeString(&GuidString, &Name[14]);
    }

    ApiReturn = RtlGUIDFromString(&GuidString, &AdapterGUID);
    if (ApiReturn != 0)
    {
        skip("RtlGUIDFromString failed. Can't proceed\n");
        return;
    }

    hIpHlpApi = GetModuleHandleW(L"iphlpapi.dll");
    if (!hIpHlpApi)
    {
        skip("Failed to load iphlpapi.dll. Can't proceed\n");
        return;
    }

    pNhGetInterfaceNameFromGuid = (void *)GetProcAddress(hIpHlpApi, "NhGetInterfaceNameFromGuid");

    if (!pNhGetInterfaceNameFromGuid)
        skip("NhGetInterfaceNameFromGuid not found. Can't proceed\n");
    else
        test_NhGetInterfaceNameFromGuid(AdapterGUID, 0, 0);

    pNhGetInterfaceNameFromDeviceGuid = (void *)GetProcAddress(hIpHlpApi, "NhGetInterfaceNameFromDeviceGuid");

    if (!pNhGetInterfaceNameFromDeviceGuid)
        skip("NhGetInterfaceNameFromDeviceGuid not found. Can't proceed\n");
    else
        test_NhGetInterfaceNameFromDeviceGuid(AdapterGUID, 1, 0);
}
Ejemplo n.º 11
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;
}
Ejemplo n.º 12
0
HRESULT RefreshIPCfgDialog(HWND hwndDlg, BOOL fRenew)
{
    PIP_ADAPTER_INFO    pAdapterInfo = NULL, pAdapterInfoHead = NULL;
    PIP_INTERFACE_INFO  pBuffer = NULL;
    HRESULT             hr = S_OK;
    ULONG               ulBufferSize = 0;
    DWORD               dwRetVal;
    HWND                hAddrTypeLbl;
    HWND                hIPAddrLbl;
    HWND                hGatewayLbl;
    HWND                hSubnetMskLbl;
    WCHAR               szIpAddr[MAX_IP_FIELD_WIDTH];
    WCHAR               szGateway[MAX_IP_FIELD_WIDTH];
    WCHAR               szSubnetMsk[MAX_IP_FIELD_WIDTH];
    WCHAR               szOldIpAddr[MAX_IP_FIELD_WIDTH];
    WCHAR               szOldGateway[MAX_IP_FIELD_WIDTH];
    WCHAR               szOldSubnetMsk[MAX_IP_FIELD_WIDTH];
    WCHAR               szOldDhcpEnabled[STRING_BUFFER_MAX];
    INT                 i;
    TCHAR               szStatic[STRING_BUFFER_MAX];
    TCHAR               szDhcp[STRING_BUFFER_MAX];
    WCHAR               szAdapterName[MAX_ADAPTERNAME_STR];

    // Get UI components
    hAddrTypeLbl        = GetDlgItem(hwndDlg, IDC_ADDRTYPE_LBL_INF);
    hIPAddrLbl          = GetDlgItem(hwndDlg, IDC_IPADDR_LBL_INF);
    hGatewayLbl         = GetDlgItem(hwndDlg, IDC_GATEWAY_LBL_INF);
    hSubnetMskLbl       = GetDlgItem(hwndDlg, IDC_SUBNETMSK_LBL_INF);

    // 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;
    }

    // If renew IP Info is specified
    if (fRenew) {
        ulBufferSize = 0;

        // Initialize interface
        dwRetVal = GetInterfaceInfo(pBuffer, &ulBufferSize);
        if (dwRetVal == ERROR_INSUFFICIENT_BUFFER) {
            pBuffer = (PIP_INTERFACE_INFO)malloc(ulBufferSize);
            if (!pBuffer) {
                DEBUGMSG(ZONE_ERROR, (TEXT("Insufficient Memory for IPInterface allocation.")));
                hr = E_FAIL;
                goto exit;
            }
            dwRetVal = GetInterfaceInfo(pBuffer, &ulBufferSize);
        }

        if (dwRetVal != NO_ERROR) {
            DEBUGMSG(ZONE_ERROR, (TEXT("NetUIQC: Could not get interface for renewing IP info")));
            hr = E_FAIL;
            goto exit;
        }

        // If no adapter interface is present
        if (ulBufferSize == 0) {
            hr = E_FAIL;
            goto exit;
        }

        SetCursor(LoadCursor(NULL, IDC_WAIT));

        if (GetAdapterNameW(hwndDlg,szAdapterName,sizeof(szAdapterName)) != S_OK) {
            hr = E_FAIL;
            goto exit;
        }

        // Loop through adpaters to find the current adapter
        for (i=0;i<pBuffer->NumAdapters;i++) {
            if (!wcscmp(pBuffer->Adapter[i].Name, szAdapterName)) {
                // Release the IP address of the specified adpater
                dwRetVal = IpReleaseAddress(&(pBuffer->Adapter[i]));

                // Reset labels based on a successful Release
                if (dwRetVal == NO_ERROR) {
                    SetWindowText(hIPAddrLbl, L"0.0.0.0");
                    SetWindowText(hSubnetMskLbl, L"0.0.0.0");
                    SetWindowText(hGatewayLbl, L"");
                    Sleep(500); // Sleep for dramatic effect
                }

                // Renew the IP address of the specified adapter
                IpRenewAddress(&(pBuffer->Adapter[i]));
            }
        }

        SetCursor(LoadCursor(NULL, IDC_ARROW));
    } else {
        // Get IP data from iphelper
        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);

        LoadString(v_hInst, IDS_QC_DHCP, szDhcp, sizeof(szDhcp)/sizeof(szDhcp[0]));
        LoadString(v_hInst, IDS_QC_STATIC_IP, szStatic, sizeof(szStatic)/sizeof(szStatic[0]));

        // Set the data in the UI components if it has changed

        GetWindowText(hAddrTypeLbl, szOldDhcpEnabled, STRING_BUFFER_MAX);
        if (wcscmp(((pAdapterInfo->DhcpEnabled) ? szDhcp : szStatic), szOldDhcpEnabled) != 0) {
            SetWindowText(hAddrTypeLbl, (pAdapterInfo->DhcpEnabled) ? szDhcp : szStatic);
        }

        GetWindowText(hIPAddrLbl, szOldIpAddr, MAX_IP_FIELD_WIDTH);
        if (wcscmp(szOldIpAddr, szIpAddr) != 0) {
            SetWindowText(hIPAddrLbl, szIpAddr);
        }

        GetWindowText(hGatewayLbl, szOldGateway, MAX_IP_FIELD_WIDTH);
        if (wcscmp(szOldGateway, szGateway) != 0) {
            SetWindowText(hGatewayLbl, szGateway);
        }

        GetWindowText(hSubnetMskLbl, szOldSubnetMsk, MAX_IP_FIELD_WIDTH);
        if (wcscmp(szOldSubnetMsk, szSubnetMsk) != 0) {
            SetWindowText(hSubnetMskLbl, szSubnetMsk);
        }
    }

    exit:

    if (pBuffer) {
        free(pBuffer);
    }
    if (pAdapterInfoHead) {
        free(pAdapterInfoHead);
    }

    return hr;

} // RefreshIPCfgDialog