c++sortingip-address

convert ip address to a single number


I have a file which contains more than 100 ip addresses(dotted decimal.eg. 169.23.43.12). Now I need to read all the ip addresses and sort in ascending order. For this, first of all I tried to convert all the ip addresses into its equivalent integer number.I created a c++ function to convert the ip addresses, but it did not work for large ip address, such as 255.250.120.100. I tried to use inet_aton() and inet_ntoa(). But using these two, I could not sort the ip addresses. So, please give me an idea to convert the ip addresses into a form which could be sorted. Below are some codes by using which I tried to sort ip address, but did not work.

struct sockaddr_in antelope[2]; char *some_addr;

inet_aton("60.0.0.4", &antelope[0].sin_addr); // store IP in antelope
inet_aton("10.0.0.2", &antelope[1].sin_addr); // store IP in antelope
std::sort(antelope,antelope+2);
cout<<inet_ntoa(antelope[0].sin_addr)<<endl;
cout<<inet_ntoa(antelope[1].sin_addr)<<endl;

Solution

  • You can do this with a custom comparator for struct sokaddr_in. The snippet below explains what I mean. The advantage of this approach is you can customize the comparator for IPv6 and to include port nos. and other stuff if IP addresses are same.

        #include <iostream>
        #include <algorithm>
        #include <arpa/inet.h>
    
    
        struct CompareSockAddr_in
        {
            bool operator ()(struct sockaddr_in ip1,struct sockaddr_in ip2){
                // use return ip1.sin_addr.s_addr < ip2.sin_addr.s_addr; for ascending order
    return ip1.sin_addr.s_addr > ip2.sin_addr.s_addr;
            }
        };
    
        int main()
        {
            struct sockaddr_in antelope[2];
    
            inet_pton(AF_INET, "10.0.0.2", &(antelope[0].sin_addr));
            inet_pton(AF_INET, "60.0.0.4", &(antelope[1].sin_addr));
    
            std::cout<<inet_ntoa(antelope[0].sin_addr)<<std::endl;
            std::cout<<inet_ntoa(antelope[1].sin_addr)<<std::endl;
            std::sort(antelope,antelope+2,CompareSockAddr_in());
    
            std::cout<<"Sorted List...\n";
    
            std::cout<<inet_ntoa(antelope[0].sin_addr)<<std::endl;
            std::cout<<inet_ntoa(antelope[1].sin_addr)<<std::endl;
    
            return 0;
        }
    

    Hope this helps.