Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

Convert IP Address to LONGWORD and Vice Versa

Title: Convert IP Address to LONGWORD and Vice Versa Question: Conversion functions to convert IP Address string to a double word and vice versa. These functions are useful in Database Design where an IP Address can be stored in a 4 bye double word as opposed to a 15 byte string. eg. var IpValue : longword; IpAddress : string; IpValue := IpToInt('196.11.175.160'); // 3289100192 IpAddress := IntToIp(3289100192); // '196.11.175.160' Answer: // NOTE : LongWord can be replaced with DWORD for Delphi // versions lower than 6 function IpToInt(const AIpAddress : string) : longword; var Retvar,i,iShift : longword; sData,sSeg : string; begin Retvar := 0; iShift := 24; sData := trim(AIpAddress); while sData '' do begin i := pos('.',sData); if i 0 then begin sSeg := copy(sData,1,i - 1); sData := copy(sData,i+1,length(sData)); end else begin sSeg := sData; sData := ''; end; Retvar := Retvar + (longword(StrToIntDef(sSeg,0)) shl iShift); dec(iShift,8); end; Result := Retvar; end; function IntToIp(AIpValue : longword) : string; var Retvar : string; iSeg,iShift, i,iMask : longword; begin Retvar := ''; iShift := 24; iMask := $FF000000; for i := 1 to 4 do begin iSeg := (AIpValue and iMask) shr iShift; Retvar := Retvar + IntToStr(iSeg); if i 4 then Retvar := Retvar + '.'; iMask := iMask shr 8; dec(iShift,8); end; Result := Retvar; end;