cosail

  博客园  :: 首页  ::  ::  ::  :: 管理

#include <stdio.h>
#include <string.h>
#include <stdlib.h>     //atoi(), 这里用不了itoa()函数(不属于标准)

//字符串形式到整数形式
int IP_str2int(const char *IP)
{
     char* token = NULL;
    int intIP = 0;
    char strIP[16];
    int lenIP = 0;

    lenIP = strlen(IP);
    memcpy(strIP, IP, lenIP);
    strIP[lenIP] = '\0';

    token = strtok(strIP, ".");
    if(NULL != token) {
        intIP |= atoi(token);
    } else {
        printf("strtok() failed!\n");
        return 0;
    }

    for(int i=1; i<4; i++) {
        if(NULL != (token = strtok(NULL, "."))) {
            intIP |= (atoi(token) << (8*i));
        } else {
            return 0;
        }
    }

    return intIP;
}

//整数形式到字符串形式
//这不是个安全的函数,容易内存访问越界(参数size主要提醒程序员要给strIP[]分配足够空间)
int IP_int2str(int IP, char strIP[], size_t size)
{
    if(size < 16) {
        perror("IP_int2str(): 参数strIP字符数组长度不应小于16!\n");
        return -1;
    }

    unsigned char aByte = 0;
    int offset = 0;

    for(int i=0; i<4; i++) {
        aByte = (IP & 0x000000FF);
        offset += sprintf(&strIP[offset], "%d", aByte);
        if(3 == i) {
            strIP[offset] = '\0';
        } else {
            strIP[offset++] = '.';
        }
        IP = IP >> 8;
    }

    return 0;
}

int main(int argc, char* argv[])
{
    int intIP = 0;
    intIP = IP_str2int("10.23.34.207");
    printf("intIP: %d\n", intIP);

#define IP_STRING_LEN   16
    char strIP[IP_STRING_LEN];
    IP_int2str(-819849462, strIP, IP_STRING_LEN);  //如果strIP分配空间不够,可能越界访问!!
    printf("strIP: %s\n", strIP);
#undef  IP_STRING_LEN
}

posted on 2014-04-08 22:48  cosail  阅读(1611)  评论(0编辑  收藏  举报