How to use IP address in integer format?

Discussion of open issues, suggestions and bugs regarding MyDAC (Data Access Components for MySQL) for Delphi, C++Builder, Lazarus (and FPC)
Post Reply
davor.TCS
Posts: 29
Joined: Thu 05 Apr 2012 22:10
Contact:

How to use IP address in integer format?

Post by davor.TCS » Fri 06 Apr 2012 06:57

I have in my MySQL table IPaddress of some devices. They are represented as int values.
I would like to translate those addresses to user in dotted view (example 192.168.1.111).
I am working in Delphi and with TTable.
Which filed type I should select when creating fields in TTable?
How can I set this as string for the user? And save as integer?

AndreyZ

Post by AndreyZ » Fri 06 Apr 2012 13:20

I've answered you by e-mail.

davor.TCS
Posts: 29
Joined: Thu 05 Apr 2012 22:10
Contact:

Post by davor.TCS » Mon 09 Apr 2012 08:19

Hi im postin yours reply if someone needs it:

//********************************
You can create persistent fields in your dataset and use the OnGetText and OnSetText to display IP adresses in any way you like. Here is an example:
procedure TMainForm.MyQueryIPGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
begin
Text := Sender.AsString;
// here you can change the display value of IP adresses
end;

procedure TMainForm.MyQueryIPSetText(Sender: TField; const Text: String);
begin
// here you can format the IP adress string to integer value
Sender.AsInteger := StrToInt(Text);
end;
//********************************

and reply:
Yes, I also googled that one, that is ok, but...
if I declare my persistent field as integer and I use code as you sent me, I can not change ip address?
That is I can not type in a dot (.)!? I can type any numbers in DBGrid(DBEdit) but not dot (.)!?
If on other hand if I declare persistent field as string when loading data MyDAC will report that field types does not match (which is ok because they do not).
I have sended you an example by mail. Maybe I am doing something wrong here...

AndreyZ

Post by AndreyZ » Mon 09 Apr 2012 10:11

This problem occurs because the TIntegerField class doesn't allow inputing non-digit symbols. To solve the problem, you can use casting. For example, you can use the following SQL statement:

Code: Select all

select id, cast(ip as char) ip from testip
In this case, you will work with string values and be able to input the '.' symbol. I have sent you your example with all needed corrections.

zat
Posts: 23
Joined: Tue 21 Jun 2011 13:08

Post by zat » Wed 11 Apr 2012 13:23

May be use Mysql function ?

mysql> SELECT INET_ATON('10.0.5.9');

Result: -> 167773449

mysql> SELECT INET_NTOA(167773449);

Result: -> '10.0.5.9'

Type data field in DB - unsigned int
This work fine for store and sort, and find, and display result for users.

Post Reply