Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

How to convert a normal IP Address to a DWord IP Address

Title: How to convert a normal IP Address to a DWord IP Address Question: We sometimes link to a URL like "http://3232235778". This notation is known as DWord IP Address. How can we convert a regular IP Address to a DWord IP Address. Answer: The following Function may not be the most elegante one, but it works. The function will convert an IP Address passed as a string, and returns a string with the converted DWord value. You can test the result with the "Ping" command. NOTE: you must add "Math" to "Uses" for the "IntPower" Function; ****************************************************************** This code is FREE. It was compiled on Delphi 3. ****************************************************************** Function IP2HEX(OrgIP:String):String; Var OrgVal:String; // Saved Original IP Address O1,O2,O3,O4:String; // Original IP Split H1,H2,H3,H4:String; // Octet To Hex HexIP:String; // All Hex Strings United XN:Array[1..8] of Extended; Flt1:Extended; Xc:Integer; Begin // Save in reverse order for easy "Case" Xn[8]:=IntPower(16,0);Xn[7]:=IntPower(16,1);Xn[6]:=IntPower(16,2);Xn[5]:=IntPower(16,3); Xn[4]:=IntPower(16,4);Xn[3]:=IntPower(16,5);Xn[2]:=IntPower(16,6);Xn[1]:=IntPower(16,7); // Save Original IP Address OrgVal:=OrgIP; O1:=Copy(OrgVal,1,Pos('.',OrgVal)-1);Delete(OrgVal,1,Pos('.',OrgVal)); O2:=Copy(OrgVal,1,Pos('.',OrgVal)-1);Delete(OrgVal,1,Pos('.',OrgVal)); O3:=Copy(OrgVal,1,Pos('.',OrgVal)-1);Delete(OrgVal,1,Pos('.',OrgVal)); O4:=OrgVal; H1:=IntToHex(StrToInt(O1),2);H2:=IntToHex(StrToInt(O2),2); H3:=IntToHex(StrToInt(O3),2);H4:=IntToHex(StrToInt(O4),2); // Here we have the HEX value of IP Address HexIP:=H1+H2+H3+H4; // Start Convert Huge HEX to Float variable Flt1:=0; For Xc:=1 to 8 do Begin Case HexIP[Xc] of '0'..'9':Flt1:=Flt1+(StrToInt(HexIP[XC])*Xn[Xc]); 'A':Flt1:=Flt1+(10*Xn[Xc]); 'B':Flt1:=Flt1+(11*Xn[Xc]); 'C':Flt1:=Flt1+(12*Xn[Xc]); 'D':Flt1:=Flt1+(13*Xn[Xc]); 'E':Flt1:=Flt1+(14*Xn[Xc]); 'F':Flt1:=Flt1+(15*Xn[Xc]); End; End; Result:=FloatToStr(Flt1); End;