March 3, 2012

Klondike6 Klondike6
Lab Rat
17 posts

IP Address conversion from string to unsigned int

 

I have a QString where the user provides an IP address like “192.168.0.128” and I need to convert this to the corresponding 32-bit unsigned int value (0xC0A80080). Is there a recommended way to do this?

Of course, I could come up with my own method to parse the string and do the conversion, but I’m sure there are many applications that do this already – I don’t want to reinvent it if Qt already provides something like this.

Thanks for any guidance you can provide.

6 replies

March 3, 2012

koahnig koahnig
Mad Scientist
2199 posts

Use QHostAddress::toIPv4Address [qt-project.org]

March 3, 2012

Klondike6 Klondike6
Lab Rat
17 posts

I did try using QHostAddress, but had problems with unresolved externals, couldn’t find the methods in QHostAddress – ???

Anyway, here is an alternative approach:

I have a QString called Server_IP containing something like “192.168.0.128”. The code below converts this to a 32-bit value (serverIPnum):

  1.             QStringList server_octets = Server_IP.split(".");
  2.             s1 = server_octets.at(0).toLong();
  3.             s2 = server_octets.at(1).toLong();
  4.             s3 = server_octets.at(2).toLong();
  5.             s4 = server_octets.at(3).toLong();
  6.             serverIPnum = (s1 << 24) | (s2 << 16) | (s3 << 8) | s4;

Maybe not very elegant, but it works.

March 3, 2012

d2uriel d2uriel
Lab Rat
71 posts

Have you added QtNetwork module to your project? Probably not and that’s why you had unresolved external errors.

 Signature 

“Do not judge, and you will never be mistaken.” - Jean-Jacques Rousseau

March 3, 2012

koahnig koahnig
Mad Scientist
2199 posts

d2uriel is probably right that you did not include QNetwork module.

Please use code wrappings [qt-project.org] next time. I have added them for you.

March 3, 2012

Klondike6 Klondike6
Lab Rat
17 posts

I had included QtNetwork, still had the unresolved externals. Not really an issue anymore since I am using my alternative approach.

March 4, 2012

d2uriel d2uriel
Lab Rat
71 posts

You added that to the .PRO file and ran QMake afterwards?

Anyways, as you say, case is closed.

 Signature 

“Do not judge, and you will never be mistaken.” - Jean-Jacques Rousseau

 
  ‹‹ [SOLVED] Setting 8bit alpha channel/mask to QPixmap?      getting frame bits data from video stream ››

You must log in to post a reply. Not a member yet? Register here!