Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I am not getting correct ip address and ip mask.
other values are correct for index, broadcast, Re assembly size.

How to get correct ip address and ip mass using GetIpAddrTable?

C++
#pragma comment(lib,"IPHlpApi.Lib")
#pragma comment(lib, "ws2_32.lib")

#include "windows.h"
#include "iphlpapi.h"		//IP Helper api

LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow)
{
     static TCHAR szAppName[] = TEXT ("Ip Address") ;
     HWND         hwnd ;
     MSG          msg ;
     WNDCLASS     wndclass ;

     wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
     wndclass.lpfnWndProc   = WndProc ;
     wndclass.cbClsExtra    = 0 ;
     wndclass.cbWndExtra    = 0 ;
     wndclass.hInstance     = hInstance ;
     wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
     wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
     wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
     wndclass.lpszMenuName  = NULL ;
     wndclass.lpszClassName = szAppName ;

     if (!RegisterClass (&wndclass))
     {
          MessageBox (NULL, TEXT ("This program requires Windows NT!"), 
                      szAppName, MB_ICONERROR) ;
          return 0 ;
     }
     
     hwnd = CreateWindow (szAppName,                  // window class name
                          TEXT ("Ip Address"), // window caption
                          WS_OVERLAPPEDWINDOW,        // window style
                          CW_USEDEFAULT,              // initial x position
                          CW_USEDEFAULT,              // initial y position
                          CW_USEDEFAULT,              // initial x size
                          CW_USEDEFAULT,              // initial y size
                          NULL,                       // parent window handle
                          NULL,                       // window menu handle
                          hInstance,                  // program instance handle
                          NULL) ;                     // creation parameters
     
     ShowWindow (hwnd, iCmdShow) ;
     UpdateWindow (hwnd) ;
     
     while (GetMessage (&msg, NULL, 0, 0))
     {
          TranslateMessage (&msg) ;
          DispatchMessage (&msg) ;
     }
     return msg.wParam ;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
     HDC         hdc ;
     PAINTSTRUCT ps ;
     RECT        rect ;
	 TCHAR szName[] = TEXT ("IP ADDRESS") ;
	 
	 MIB_IPADDRTABLE  *pIPAddrTable;
	 DWORD            dwSize = 0;
	 DWORD            dwRetVal;

	 struct in_addr  inAddr;

	//For error : GetIpAddrTable call failed
	 int iLength;
	 TCHAR szBuffer[40],szBuffer1[40],szBuffer2[40],szBuffer3[40],szBuffer4[40],szBuffer5[40];
	     
     switch (message)
     {
           
     case WM_PAINT:
          hdc = BeginPaint (hwnd, &ps) ;

          GetClientRect (hwnd, &rect) ;
          
          TextOut(hdc,0,1,szName,lstrlen(szName));

		  pIPAddrTable = (MIB_IPADDRTABLE*) malloc( sizeof(MIB_IPADDRTABLE) );
		  /* Get size required by GetIpAddrTable() */
		  //The GetIpAddrTable function retrieves the interface–to–IPv4 address mapping table.
		    if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
			{
				free( pIPAddrTable );
				pIPAddrTable = (MIB_IPADDRTABLE *) malloc ( dwSize );
				TextOut(hdc,0,120,szBuffer,iLength = wsprintf(szBuffer, TEXT("memory %d"),dwRetVal));
			}

		  /* Get actual data using GetIpAddrTable() */
			if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) != NO_ERROR )
			{ 
				TextOut(hdc,0,20,szBuffer,iLength = wsprintf(szBuffer, TEXT("GetIpAddrTable call failed with %d"),dwRetVal));
			}
			if ( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) == NO_ERROR )
			{ 
				TextOut(hdc,0,140,szBuffer,iLength = wsprintf(szBuffer, TEXT("no error %d"),dwRetVal));
			}
			
			memmove (&inAddr, &(pIPAddrTable->table[0].dwAddr), 4);

			TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address        : %s "), inet_ntoa(inAddr)));
			TextOut(hdc,0,40,szBuffer2,iLength = wsprintf(szBuffer2, TEXT("IP Mask           : %i "), pIPAddrTable->table[0].dwMask));
			TextOut(hdc,0,60,szBuffer3,iLength = wsprintf(szBuffer3, TEXT("IF Index          : %i "), pIPAddrTable->table[0].dwIndex));
			TextOut(hdc,0,80,szBuffer4,iLength = wsprintf(szBuffer4, TEXT("Broadcast Addr    : %i "), pIPAddrTable->table[0].dwBCastAddr));
			TextOut(hdc,0,100,szBuffer5,iLength = wsprintf(szBuffer5, TEXT("Re-assembly size : %i "), pIPAddrTable->table[0].dwReasmSize));


		  EndPaint (hwnd, &ps) ;
          return 0 ;
          
     case WM_DESTROY:
          PostQuitMessage (0) ;
          return 0 ;
     }
     return DefWindowProc (hwnd, message, wParam, lParam) ;
}
Posted
Updated 27-Feb-12 21:21pm
v2
Comments
Jochen Arndt 28-Feb-12 3:38am    
You may add the output of your program and the expected result (ipconfig output) to your question. Your program shows only the first entry from the result table. You may add a loop to show all results.
amityadav4a 28-Feb-12 6:28am    
if( (dwRetVal = GetIpAddrTable( pIPAddrTable, &dwSize, 0 )) == NO_ERROR )
{
TextOut(hdc,0,140,szBuffer,iLength = wsprintf(szBuffer, TEXT("no error %d"),dwRetVal));
if(pIPAddrTable->dwNumEntries>0)
{
for(DWORD i=0;i<=pIPAddrTable->dwNumEntries;i++)
{
memmove (&inAddr, &(pIPAddrTable->table[i].dwAddr), 4);

TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address : %s "), inet_ntoa(inAddr)));
TextOut(hdc,0,40,szBuffer2,iLength = wsprintf(szBuffer2, TEXT("IP Mask : %i "), pIPAddrTable->table[i].dwMask));
TextOut(hdc,0,60,szBuffer3,iLength = wsprintf(szBuffer3, TEXT("IP Index : %i "), pIPAddrTable->table[i].dwIndex));
TextOut(hdc,0,80,szBuffer4,iLength = wsprintf(szBuffer4, TEXT("Broadcast Addr : %i "), pIPAddrTable->table[i].dwBCastAddr));
TextOut(hdc,0,100,szBuffer5,iLength = wsprintf(szBuffer5, TEXT("Re-assembly size : %i "), pIPAddrTable->table[i].dwReasmSize));
}
}
}

Using this loop i am getting values as

IP Address: ||||||||||||
IP Mask: -842150451
IP Index: -842150451
Broadcase Adr: -842150451
Re-assembly size: -842150451
Jochen Arndt 28-Feb-12 6:40am    
You are looping up to and including dwNumEntries which is a buffer overrun (use i < pIPAddrTable->dwNumEntries as loop end condition) which is the reason for the wrong output overwriting the output from the first loop execution. You may also add i * 20 to the y parameters of the TextOut calls.
amityadav4a 28-Feb-12 6:48am    
i want to print ip address and ip mask in 255.255.255.0 format. How to print it?
using this for the code

TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address : %i "), pIPAddrTable->table[0].dwAddr));


Jochen Arndt 28-Feb-12 6:58am    
inet_ntoa can be used (may be bytes must be reversed). But you should use "%hs" within the wsprintf format string to ensure valid output with Unicode builds (inet_ntoa uses a static char buffer).

1 solution

G'day, just tried your code as written.

I can't see any problem with the output values. When you say that incorrect values are being displayed for ipAddress and ipMask, I don't suppose you've got a router between yourself and the net?

I ask because the IP reported by this app is different to that reported by an online "what's my ip" type site. This is normal behaviour.



When using the program on my computer, the ip address reported is the one that my pc has (EDIT: in the network made up of itself and the phone) - this is a local address since my pc is getting internet via wifi from my phone.

[EDIT:] When using an online utility, the IP reported is the one that the router has (in the network that is the web)
So, there's a local network between my pc and the phone. There's also a network between my phone and the web.

So, the phone has 2 IPs. Which one is reported depends on where the request comes from - local network or WWW.




Using the tool on my machine, I changed the format specifier for the ipMask, and added the addresses in brackets for clarity, I get the following results:

IP Address: 192.168.56.1
IP Mask: 0x00FFFFFF  (255.255.255.0)
IP Index: 20
Broadcase Adr: 1 (1.0.0.0)
Re-assembly size: 65535
memory: 0
no error: 0


Checking this against what we get from running "ipconfig" in a console window:
CSS
...
...
Ethernet adapter VirtualBox Host-Only Network:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::c8e3:104b:34f0:fd24%20
   IPv4 Address. . . . . . . . . . . : 192.168.56.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
...
...
 
Share this answer
 
v2
Comments
amityadav4a 28-Feb-12 6:10am    
I am getting output like this on my pc. Using Visual studio 2008

this is what i am using to print on window
TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address : %s "), inet_ntoa(inAddr)));

IP Address: ||||||||||||||
IP Mask: 1579415
IP Index: 2
Broadcase Adr: 1
Re-assembly size: 65535

But if i use this i am getting this value

IP Address: 1644972916
IP Mask: 1579415
IP Index: 2
Broadcase Adr: 1
Re-assembly size: 65535

Reply asap

Thank you in advance
enhzflep 28-Feb-12 6:26am    
Hehehe. :)

Welcome to the world of context!

You see, the thing is that a IP and mask are 32 bits long. Each of the 4 bytes makes up one of the 4 parts of the address. I.e these 32 bits need to be interpreted as 4 numbers that are 8 bits each.

You may visualize this as so: (disregard endianness)
IP = 0xFFEEDDCC
IP = 0xCC.0xDD.0xEE.0xFF
IP = 204.221.238.255
But, if interpreted differently(i.e as a single 32 bit number) this would be printed as 4293844428.

It was for this reason that I changed the format specifier for the IPmask from %i to %X. When displayed in hexidecimal notation it's much easier to mentally separate the 4 parts, since each of the 4 parts are 2 hexidecimal digits.

EDIT: Since you're getting 1644972916 as your IP, I suppose that your IP is actually: 116.75.12.98?
amityadav4a 28-Feb-12 6:39am    
You are absolutely correct my address is what you specified.
TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address : %X "), pIPAddrTable->table[0].dwAddr));

Now after Replacing %i with 5X i am getting this value
IP Address: 620C4B74

what specifier should i use to get ip in this format 204.221.238.255

Please Reply asap!
enhzflep 28-Feb-12 6:53am    
inet_ntoa is the function that converts a 32 bit number into the string representation of an IP.

Here's a sample for you (link with Ws2_32.lib)
Code:

#include <iostream>
#include <winsock2.h>

using namespace std;



int main()
{
char *ipAdrString;
in_addr ipAddress;

ipAddress.S_un.S_addr = 0x620C4B74;
ipAdrString = inet_ntoa(ipAddress);
cout << ipAdrString << endl;
return 0;
}

Result:
116.75.12.98

Process returned 0 (0x0) execution time : 0.064 s
Press any key to continue.
amityadav4a 28-Feb-12 7:04am    
I edited code like this

TextOut(hdc,0,20,szBuffer1,iLength = wsprintf(szBuffer1, TEXT("IP Address : %hs "), inet_ntoa(inAddr)));

used %hs and inet_ntoa function to get result in desired format.

Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900