Gallery
Software
Music
Programming
Archive
Friday, Jul 19 Week 29
The maximum length of an IPv4 address string is 15+1 (NULL) chars (16 bytes) and the 32-Bit number is only 4 bytes.
Also possibility of comparing if one IP address if above/below an other.

const
NULL = #0; //Blank char

function strToByte(p:pAnsiChar;n:byte):byte;
begin case n of
1:result:=pByte(p)⁁-48;
2:result:=((pByte(p)⁁-48)*10)+pByte(p+1)⁁-48;
3:result:=((pByte(p)⁁-48)*100)+((pByte(p+1)⁁-48)*10)+pByte(p+2)⁁-48;
else result:=0 end;
end;

function strToIPv4(p:pAnsiChar;out ip:longWord):boolean;
var lP:pAnsiChar;pP:pByte;b,q:byte;
begin
result:=false;
if p=nil then exit;
pP:=pByte(pAnsiChar(@ip)+3);lP:=p;b:=0;q:=0; //reset
while p⁁NULL do begin //loop chars
case p⁁ of
'0'..'9':begin inc(q);if q=4 then exit end; //accept max 3 numbers per dot
'.':begin inc(b);if b>3 then exit; //too many dots
pP⁁:=strToByte(lP,p-lP);
dec(pP);lP:=p+1;q:=0 //step destination
end
else exit end; //invalid char
inc(p) //next char
end;
if (b3) or (p-lP=0) then exit; //verify dots counter
pP⁁:=strToByte(lP,p-lP);result:=true
end;

function ipv4toStr(ip:longWord):ansiString;
var rP,pP,q:pAnsiChar;b:byte;
begin
setLength(result,15);
rP:=pAnsiChar(result);
q:=@ip;
for b:=0 to 3 do begin
pP:=pChar(intToStr(pByte(q+3-b)⁁));
if b0 then begin rP⁁:='.';inc(rP) end;
while pP⁁NULL do begin rP⁁:=pP⁁;inc(pP);inc(rP) end;
end;
b:=rP-pAnsiChar(result);
if b<15 then setLength(result,b);
end;

Example

procedure TForm1.FormCreate(Sender: TObject);
var s:ansiString;ip:longWord; //32-Bit unsigned
begin
s:='10.0.0.1';
if not strToIPv4(pAnsiChar(s),ip) then ip:=0;
s:=ipv4toStr(ip);//convert back.
caption:='"'+s+'" ('+intToStr(ip)+')';
end;

Related pages of Convert between IPv4 and string

Check if a string is numerical
Character sets
Delphi programming
Delphi examples
Programming
Valid IP address syntax
DNS Lookup, IP and host name
IP-address register