IP与ID的互转

多个集群环境,单个集群的浮动IP具有唯一性,因此将集群的ID以IP地址转成8位16进制的字符表示。

例如192.168.0.1,将被转码成:c0a80001,即将IP地址字符串按点分割成4个10进制整数,然后每个整数转码成2位16进制字符。

代码如下:

#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>

bool ConvertIPtoID(const string& ip, string& id)
{
    // printf("ConvertIPtoID: ip is %s\n", ip.c_str());
    id.clear();
    vector<string> ip_segs;
    split(ip_segs, ip, is_any_of("."));
    char hex_dict[] = "0123456789abcdef";
    
    for (int i = 0; i != ip_segs.size(); ++i) {
        string tmp("xx");
        int num = atoi(ip_segs[i].c_str());
        
        if (num < 0 || num > 255) {
            printf("Invalid IP address: %s", ip.c_str());
            return false;
        }
        
        tmp[0] = hex_dict[num / 16];
        tmp[1] = hex_dict[num % 16];
        id += tmp;
    }
    
    // printf("ConvertIPtoID: id is %s\n", id.c_str());
    return true;
}

bool ConvertIDtoIP(const string& id, string& ip)
{
    // printf("ConvertIDtoIP: id is %s\n", id.c_str());
    ip.clear();
    int ip_seg[4];
    
    for (int i = 0; i != 4; ++i) {
        if (id[i * 2] >= '0' && id[i * 2] <= '9') {
            ip_seg[i] = (id[i * 2] - '0') * 16;
        } else if (id[i * 2] >= 'a' && id[i * 2] <= 'f') {
            ip_seg[i] = (id[i * 2] - 'a' + 10) * 16;
        } else {
            printf("Invalid ID: %s", id.c_str());
            return false;
        }
        
        if (id[i * 2 + 1] >= '0' && id[i * 2 + 1] <= '9') {
            ip_seg[i] += (id[i * 2 + 1] - '0');
        } else if (id[i * 2 + 1] >= 'a' && id[i * 2 + 1] <= 'f') {
            ip_seg[i] += (id[i * 2 + 1] - 'a' + 10);
        } else {
            printf("Invalid ID: %s", id.c_str());
            return false;
        }
        
        char tmp[16];
        sprintf(tmp, "%d", ip_seg[i]);
        
        if (ip == "") {
            ip = string(tmp);
        } else {
            ip += string(".") + string(tmp);
        }
    }
    
    // printf("ConvertIDtoIP: ip is %s\n", ip.c_str());
    return true;
}

 

posted @ 2017-09-19 09:10  lausaa  阅读(756)  评论(0)    收藏  举报