[fpc-pascal] Test for valid ip address
Rainer Stratmann
rainerstratmann at t-online.de
Thu Jul 28 10:36:08 CEST 2016
The IP-Adress is a dword, but you can change, that it fits for you.
function str_getval( str : shortstring ) : longint;
var cod : longint;
begin
val( str , result , cod );
end;
function ip_from_string( ipstr : shortstring ; out error : boolean ) : dword;
var
c : char;
ipn , pointanz : longint;
x : longint;
pstr : shortstring;
ip : dword;
procedure add_ip;
begin
ipn := str_getval( pstr );
if ( ipn > 255 ) or ( pstr = '' ) then error := true;
ip := ip shl 8;
ip := ip or ipn;
pstr := '';
end;
begin
ip := 0;
pstr := '';
error := false;
pointanz := 0;
for x := 1 to length( ipstr ) do begin
c := ipstr[ x ];
case c of
'0'..'9' : pstr := pstr + c;
'.' : begin
inc( pointanz );
add_ip;
end;
else error := true;
end;
end;
add_ip;
if pointanz <> 3 then error := true;
if error then result := 0
else result := ip;
end;
Am Donnerstag, 28. Juli 2016, 10:14:10 schrieb Koenraad Lelong:
> Hi,
>
> I need a way to test if an string containing an ipv4-address is really
> an ipv4-address.
> I tried
> tmpAddress:=HostAddrToStr(StrToHostAddr(IPAddressStr));
> writeln(tmpAddress);
> if (tmpAddress='0.0.0.0') then
> begin
> writeln('Error in IP-address');
> IPAddressStr:=tmpAddress;
> end;
> When I enter 192.168.185.297 (i.e. not a valid ipv4 address) in
> IPAddressStr I get
> 192.168.185.41
> not the expected error-message.
>
> According to the rtl-manual :
>
> function StrToHostAddr(IP: AnsiString) : in_addr
> Description: StrToHostAddr converts the string representation in IP to a
> host address and returns the host
> address.
> Errors: On error, the host address is filled with zeroes.
>
> I would think that converting those zeroes to a host-address would yield
> 0.0.0.0.
>
> Am I missing something ?
> Is there a better way, without using some other network-library ?
>
> Koenraad.
> _______________________________________________
> fpc-pascal maillist - fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal
More information about the fpc-pascal
mailing list