Search This Blog

Thursday, March 26, 2009

CIPAddressCtr converting CString IP address to DWORD

CIPAddressCtr converting CString IP address to DWORD



DWORD GetDWORDIPAddress(CString strIPAddress)
{
     strIPAddress.MakeReverse();// Start from behind

     char DOT = '.';
     DWORD dwReturnValue = 0;

     double dPower = 0.0;

     int length = strIPAddress.GetLength();

     DWORD dwByteTemp = 0;
     int nWhichByte = 0;
     int i = 0;
     for(i; i<length ; i++ ){
          volatile int nTemp = 0;
          char aChar = strIPAddress.GetAt(i);

          if(aChar != DOT){
               int nChar = 0;
               switch(aChar){
                    case '1': nChar = 1; break;
                    case '2': nChar = 2; break;
                    case '3': nChar = 3; break;
                    case '4': nChar = 4; break;
                    case '5': nChar = 5; break;
                    case '6': nChar = 6; break;
                    case '7': nChar = 7; break;
                    case '8': nChar = 8; break;
                    case '9': nChar = 9; break;
                    case '0': nChar = 0; break;
                    default: break;
               }
               nTemp = nChar * (int)pow(10.0 ,dPower);
               dwByteTemp += nTemp;
               dPower++;

               if(i == length-1/*Last Byte*/){
                    dwByteTemp <<= (nWhichByte * 8);//8 Bits = Byte Length
                    dwReturnValue = dwReturnValue | dwByteTemp;
                    dPower = 0;
                    dwByteTemp = 0;
                    nWhichByte++;
               }
          } else {
               dwByteTemp <<= (nWhichByte * 8);// 8 Bits = Byte Length
               dwReturnValue = dwReturnValue | dwByteTemp;
               dPower = 0;
               dwByteTemp = 0;
               nWhichByte++;
          }
     }
     strIPAddress.MakeReverse();//Undo
     return dwReturnValue;
}

Example:

CIPAddressCtrl obj;
DWORD dwIP,dwSubnet,dwGateway,dwProxy;
dwIP=GetDWORDIPAddress(csIP);
dwSubnet=GetDWORDIPAddress(csSubnet);
dwGateway=GetDWORDIPAddress(csGateway);
dwProxy=GetDWORDIPAddress(csProxyIP);

No comments: