[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 484
  • Last Modified:

Code to connect with internet

Hi
I have a external network adapter and want to program it.

I plugged it into a computer and want to connect it to internet programmatically in c++.

I can retrieve MAC address of the adapter by using IpHelper GetAdapterAddresses().
I want to connect that adapter with internet using C++. So far when I retrieve IP address it gives me 0.0.0.0 IP address. The reason is understandable, because I have just plugged in the adapter, I have not connect it with internet. I want to connect it with internet and get IP address using C++. My question may have the following answer, (Note the language is C++)
1. Connect with internet
2. Automatically get IP address from DHCP server.

But I dont know how to do this in c++.

Looking for your response.

Best Regards
-- Azam
0
thisisazam
Asked:
thisisazam
  • 3
  • 2
  • 2
1 Solution
 
drichardsCommented:
You need to be on a network with a DHCP server and a gateway to the Internet if you want an address automatically.  C++ code has nothing to do with it.  You can manually assign an IP address to your adapter even if you do not have a DHCP server, but you still need a gateway to the Internet if you want to connect to a device out on the Internet.

Once you get that far you can connect to thiings on the Internet, but what exactly do you mean by "connect with Internet"?  What you want to do will determine how you do it.
0
 
thisisazamAuthor Commented:
Hi
Thanks for your reply.
Actually, When I plug in the network adapter, my computer do find it.
When I query MAC address and IP address using IPHelper APIs, I see correct MAC address, but I dont get ip address. I actually get 0.0.0.0. I confirm it by ipconfig command as well.
When I use the software came with network adapter CD, it has one button "CONNECT". When I press this CONNECT button then I get correct IP address.

I don't want to use that software, I want to connect and get ip address by my application.

I think it would be better if I mention the reason why I am doing this.
Well...
I have a network card which is connected with COM port. I have two applications, App1, which is a simple form came with the network CD. This has one button "CONNECT", when I press his button, the network card get connected with internet and get IP address. I can use that interface to send packets afterward.
I have another application App2, which I am developing in c++. App2 is supposed to connect with the same COM port, but this port is being in use by App1. so there is sharing violence.
The solution could be either of two,
1. I could use same com port by these applications simultaneously.
2. I should not use App1 to get IP address. App2 should be used to get IP address.

More detail...
Hope you understand my problem
Best Regards
Azam
0
 
ChizlCommented:
I'm a little confused, because when you start mentioning COM Ports, I think Serial, which would be why you get a shared violation.  Yes only one application can use a serial port at a time, but that has nothing to do with the NIC these days.   The software that your talking about only enables the NIC.  So it sounds to me your wanting to Enable and Disable the NIC via your software, is this correct?   There used to be API's for configuration on network devices, however, a lot of that has been removed.    Microsoft is starting to let people do somethings through WMI like enabling/disabling a NIC.
http://msdn.microsoft.com/en-us/library/aa390385.aspx

Security being Microsoft's top priority lately has made it very difficult for people like ourselves.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
drichardsCommented:
If you have a network card, then the second app does not need to connect again.  Once you are connected amd have an IP address, you should be opening sockets, not writing to a COM port.  This is like the old days of dial-up Internet.  Usually the browser triggered the phone to dial and make the connection and then other apps just used the network, happily unaware that they were going over the phone line.  It should be the same with your network adapter.  If it is already connected, your app should be able to use the established connection.
0
 
thisisazamAuthor Commented:
Hi
Thanks both of you for reply.

drichards!
I am trying to detect Current Acces technology eg. HSPA, GSM, LTE etc. I have not find anyway to  do this except writing AT command to com port where my 3G card is connected. I would be greatly appriciate if please tell me any way to find cuurent access technology of mobile device (other than AT command.)

Chizl!
Thanks for your help.
I tried WMI to enable the network adapter. The WMI works fine when I retreive any property of Win32_NetworkAdapter eg. DeviceID, Name, Description etc.
I can retreive the property of network adapter by following code , but I dont know how to call Enable Method of this class.
 The code is
-------------------------
IEnumWbemClassObject* pEnumerator = NULL;

    hres = pSvc->ExecQuery(bstr_t("WQL"),
                                          bstr_t("SELECT * FROM Win32_NetworkAdapter"), //  Where NetEnabled=True
                                          //bstr_t("SELECT * FROM MSNdis_80211_ReceivedSignalStrength"),
                                      WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
                                          NULL,
                                          &pEnumerator);
   
    if (FAILED(hres))
    {
        cout << "Query for operating system name failed."
            << " Error code = 0x"
            << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        return 1;               // Program has failed.
    }

    // Step 7: -------------------------------------------------
    // Get the data from the query in step 6 -------------------
 
    IWbemClassObject *pclsObj;
      //IWbemClassObject *ptemp;
    ULONG uReturn = 0;
   
    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;

            
            
        // Get the value of the Name property
            
            hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
                wcout << " Name: " << vtProp.bstrVal << endl;

            
       VariantClear(&vtProp);
    }

    // Cleanup
    // ========
_________________
0
 
ChizlCommented:
I use the following to help gather some information that your asking to do.   The first one below will check for the fastest adapter.  For example of you have a computer with 2 NIC's, this code will actually find which is the one that will be used for accessing, "www.chizl.com".   You can modify this method to pass in the domain.   The other is for getting MAC address and the last for getting the adapter name.   None of this uses WMI, but is much faster.    But the enabling of the NIC is the link I posted earlier, however it looks to only work under 2008 server.    I'm still doing some research, there has to be a way to do it with 2003 for example.
bool CWSock::GetBestIP(string* strIP)
{
	bool bPassed = true;
	string szIPAddr = "";
	MIB_IPADDRTABLE *pTable = new MIB_IPADDRTABLE[50];
 
	try
	{
		//get ignite IP Address
		GetIPofHost("www.chizl.com", &szIPAddr);
 
		DWORD dwSzBuff = 50 * sizeof(MIB_IPADDRTABLE);
		memset(pTable, 0, dwSzBuff);
		DWORD ret = GetIpAddrTable(pTable, &dwSzBuff, TRUE);
		if(ret == NO_ERROR && pTable->dwNumEntries)
		{
			DWORD dwIdx = 0xffffffff;
			//find the fastest interface to get to ignite's website
			DWORD dResponse = GetBestInterface(inet_addr(szIPAddr.c_str()), &dwIdx);
 
			if(!dResponse && dwIdx != 0xffffffff)
			{
				//loop through interfaces
				for(int i=0; i<pTable->dwNumEntries; i++)
				{
					//pIPNetRow = &(pTable->table[i]);
					if(pTable->table[i].dwIndex == dwIdx)
					{
						in_addr inaddr;
						inaddr.S_un.S_addr = pTable->table[i].dwAddr;
						*strIP = inet_ntoa(inaddr);
						break;
					}
				}
			}
			else
			{
				*strIP = "0.0.0.0";
				bPassed = false;
			}
		}
		else
		{
			*strIP = "0.0.0.0";
			bPassed = false;
		}
	}
	catch(...)
	{
		*strIP = "0.0.0.0";
		bPassed = false;
	}
 
	delete pTable;
 
	return bPassed;
}
 
bool CWSock::GetMACAddress(string szIP, string* szMAC)
{
	ULONG   ulMACAddr[2],
			ulSize = 6;
	LPBYTE  pBuffer; 
	bool bPassed = true;
 
	if (SendARP(inet_addr(szIP.c_str()), 0, 
						  ulMACAddr, &ulSize) == NO_ERROR)
	{
		pBuffer = (LPBYTE) ulMACAddr; 
		char pstrMAC[18] = {0};
		
		sprintf(pstrMAC, "%02X-%02X-%02X-%02X-%02X-%02X", 
			pBuffer[0], pBuffer[1], 
			pBuffer[2], pBuffer[3], 
			pBuffer[4], pBuffer[5]);
 
		*szMAC = pstrMAC;
	} else
		bPassed = false;
 
	return bPassed;
}
 
bool CWSock::GetAdapterName(string szIP, string* szNICName)
{
	//http://www.codeproject.com/KB/IP/bsipconfig.aspx
	PIP_ADAPTER_INFO pCurAdapt;
	IP_ADAPTER_INFO buffer[10];
	ULONG len = sizeof(IP_ADAPTER_INFO)*10;
	DWORD res;
	bool bPassed = false;
 
	res = GetAdaptersInfo(buffer, &len);	// fill buffer by structures
 
	if (res == ERROR_SUCCESS)
	{
		pCurAdapt = &buffer[0];		// get pointer to the first structure
 
		do {
			char pstr[1024] = {0};
 
			PIP_ADDR_STRING pCurIP = &(pCurAdapt->IpAddressList);
			sprintf(pstr, pCurIP->IpAddress.String);
 
			if(strcmp(szIP.c_str(), pstr)==0)
			{
				*szNICName = pCurAdapt->Description;
				bPassed = true;
				break;
			}
		} while ((pCurAdapt = pCurAdapt->Next) != NULL); // pCurAdapt->Next is NULL
	}
 
	return bPassed;
}

Open in new window

0
 
ChizlCommented:
You may also want to look at:  Win32_NetworkAdapterConfiguration

I found a vbs below on: http://msdn.microsoft.com/en-us/library/aa394217.aspx
sub appendCollection(msg, colctn, nm)
i=0
for each t in colctn
msg = msg & "nic." & nm & "["&i&"]: " & t & vbCRLF
i = i + 1
next
end sub
 
strComputer = "."
 
 
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 
Set colNicConfigs = objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
for each nic in colNicConfigs
msg = "nic.ArpAlwaysSourceRoute: " & nic.ArpAlwaysSourceRoute & vbCRLF _
& "nic.ArpUseEtherSNAP: " & nic.ArpUseEtherSNAP & vbCRLF _
& "nic.Caption: " & nic.Caption & vbCRLF _
& "nic.DatabasePath: " & nic.DatabasePath & vbCRLF _
& "nic.DeadGWDetectEnabled: " & nic.DeadGWDetectEnabled & vbCRLF _
& "nic.DefaultTOS: " & nic.DefaultTOS & vbCRLF _
& "nic.DefaultTTL: " & nic.DefaultTTL & vbCRLF _
& "nic.Description: " & nic.Description & vbCRLF _
& "nic.DHCPEnabled: " & nic.DHCPEnabled & vbCRLF _
& "nic.DHCPLeaseExpires: " & nic.DHCPLeaseExpires & vbCRLF _
& "nic.DHCPLeaseObtained: " & nic.DHCPLeaseObtained & vbCRLF _
& "nic.DHCPServer: " & nic.DHCPServer & vbCRLF _
& "nic.DNSDomain: " & nic.DNSDomain & vbCRLF _
& "nic.DNSEnabledForWINSResolution: " & nic.DNSEnabledForWINSResolution & vbCRLF _
& "nic.DNSHostName: " & nic.DNSHostName & vbCRLF _
& "nic.DomainDNSRegistrationEnabled: " & nic.DomainDNSRegistrationEnabled & vbCRLF _
& "nic.DNSDomainSuffixSearchOrder: " & nic.DNSDomainSuffixSearchOrder & vbCRLF _
& "nic.ForwardBufferMemory: " & nic.ForwardBufferMemory & vbCRLF _
& "nic.FullDNSRegistrationEnabled: " & nic.FullDNSRegistrationEnabled & vbCRLF _
& "nic.IGMPLevel: " & nic.IGMPLevel & vbCRLF _
& "nic.Index: " & nic.Index & vbCRLF _
& "nic.IPConnectionMetric: " & nic.IPConnectionMetric & vbCRLF _
& "nic.IPEnabled: " & nic.IPEnabled & vbCRLF _
& "nic.IPFilterSecurityEnabled: " & nic.IPFilterSecurityEnabled & vbCRLF _
& "nic.IPPortSecurityEnabled: " & nic.IPPortSecurityEnabled & vbCRLF _
& "nic.IPUseZeroBroadcast: " & nic.IPUseZeroBroadcast & vbCRLF _
& "nic.IPXAddress: " & nic.IPXAddress & vbCRLF _
& "nic.IPXEnabled: " & nic.IPXEnabled & vbCRLF _
& "nic.IPXFrameType: " & nic.IPXFrameType & vbCRLF _
& "nic.IPXMediaType: " & nic.IPXMediaType & vbCRLF _
& "nic.IPXNetworkNumber: " & nic.IPXNetworkNumber & vbCRLF _
& "nic.IPXVirtualNetNumber: " & nic.IPXVirtualNetNumber & vbCRLF _
& "nic.KeepAliveInterval: " & nic.KeepAliveInterval & vbCRLF _
& "nic.KeepAliveTime: " & nic.KeepAliveTime & vbCRLF _
& "nic.MACAddress: " & nic.MACAddress & vbCRLF _
& "nic.MTU: " & nic.MTU & vbCRLF _
& "nic.NumForwardPackets: " & nic.NumForwardPackets & vbCRLF _
& "nic.PMTUBHDetectEnabled: " & nic.PMTUBHDetectEnabled & vbCRLF _
& "nic.PMTUDiscoveryEnabled: " & nic.PMTUDiscoveryEnabled & vbCRLF _
& "nic.ServiceName: " & nic.ServiceName & vbCRLF _
& "nic.SettingID: " & nic.SettingID & vbCRLF _
& "nic.TcpipNetbiosOptions: " & nic.TcpipNetbiosOptions & vbCRLF _
& "nic.TcpMaxConnectRetransmissions: " & nic.TcpMaxConnectRetransmissions & vbCRLF _
& "nic.TcpMaxDataRetransmissions: " & nic.TcpMaxDataRetransmissions & vbCRLF _
& "nic.TcpNumConnections: " & nic.TcpNumConnections & vbCRLF _
& "nic.TcpUseRFC1122UrgentPointer: " & nic.TcpUseRFC1122UrgentPointer & vbCRLF _
& "nic.TcpWindowSize: " & nic.TcpWindowSize & vbCRLF _
& "nic.WINSEnableLMHostsLookup: " & nic.WINSEnableLMHostsLookup & vbCRLF _
& "nic.WINSHostLookupFile: " & nic.WINSHostLookupFile & vbCRLF _
& "nic.WINSPrimaryServer: " & nic.WINSPrimaryServer & vbCRLF _
& "nic.WINSScopeID: " & nic.WINSScopeID & vbCRLF _
& "nic.WINSSecondaryServer: " & nic.WINSSecondaryServer & vbCRLF _
'& "nic.InterfaceIndex: " & "|"&nic.InterfaceIndex & vbCRLF _
 
appendCollection msg, nic.DefaultIPGateway, "DefaultIPGateway"
appendCollection msg, nic.DNSServerSearchOrder, "DNSServerSearchOrder"
appendCollection msg, nic.GatewayCostMetric, "GatewayCostMetric"
appendCollection msg, nic.IPAddress, "IPAddress"
appendCollection msg, nic.IPSecPermitIPProtocols, "IPSecPermitIPProtocols"
appendCollection msg, nic.IPSecPermitTCPPorts, "IPSecPermitTCPPorts"
appendCollection msg, nic.IPSecPermitUDPPorts, "IPSecPermitUDPPorts"
appendCollection msg, nic.IPSubnet, "IPSubnet"
 
WScript.Echo msg
next
 
'Vista only code???
'Set colAdapters = objWMIService.Execquery ("SELECT * FROM Win32_NetworkAdapter WHERE NetEnabled = True")
'For Each nic in colAdapters
' msg = "nic.DeviceId: " & nic.DeviceId & vbCRLF _
' & "nic.Name: " & nic.Name & vbCRLF _
'
'Next

Open in new window

0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now