I have several IP addresses:

192.168.0.2 , 192.168.0.3 , 192.168.0.4 , 192.168.0.5 

These IP addresses need to be written into the array my_ip_address [4]. But what type of array should be my_ip_address [4], so that it is convenient and error-free to work with it?

  • uint32_t is, of course, for IPv4 - avp

5 answers 5

Traditionally, an IPv4 address is represented as an unsigned int , or just an int (see, for example, the PHP function ip2long ). Representation as a signed integer creates some problems when sorting, so the unsigned int best.

IP conversion <-> int:

    It depends on how you use the address information later. Keep it in the form in which you use it, that is, you insert it into the function call.

      If you want to save memory (for four addresses - irrelevant), then the array from uint32_t will do (four numbers from 0 to 255 are just four bytes).

      Another option, simpler is an array from std::string .

      • And if the IP addresses will be more than 4? Suppose 100. Which type is better to use then? - Glonge
      • @Glonge Depending on what you do with them. Try both options, measure time and memory consumption. Then you can find out exactly what is best in your case. - HolyBlackCat
      • Ok, thanks a lot! - Glonge

      It depends on what you want to get. It should be convenient to work with

       vector<string> 

      True, this is not appropriate if you intend to process them as numbers. then I advise you to do so.

      1) read the address as a string

      2) split by points and get at the output an array of strings

      3) then sum up everything in such a way

      Example 192.168.0.2

       192* 100000 + 168*100 +0*10+ 2 = 19216802 

      and then in vector<int>my_ip_address

      • And what is a vector ? Well, I mean, if the string is responsible for the string, and vector? - Aqua
      • The vector is essentially the same array, only with MUCH more flexible structure. - Awesome Man
      • array on Pontah))) Thank you, I understood - Aqua Nov.

      I would make any such association:

       typedef union { unsigned char parts[4]; unsigned int whole; } IPAddress;