2011年4月13日 星期三

覺得以後會用到---string_to_ip and ip_to string

(用 gcc 編,不要用DevC++) 
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

#define CONFIG_IPADDR "192.168.0.20"
typedef ulong IPaddr_t;

unsigned long simple_strtoul(const char *cp,char **endp,unsigned int base)
{
    unsigned long result = 0,value;

    if (*cp == '0') {
        cp++;
        if ((*cp == 'x') && isxdigit(cp[1])) {
            base = 16;
            cp++;
        }
        if (!base) {
            base = 8;
        }
    }
    if (!base) {
        base = 10;
    }
    while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp)
        ? toupper(*cp) : *cp)-'A'+10) < base) {
        result = result*base + value;
        cp++;
    }
    if (endp)
        *endp = (char *)cp;
    return result;
}

void ip_to_string (IPaddr_t x, char *s)
{
    x = ntohl (x);
    sprintf (s, "%d.%d.%d.%d",
         (int) ((x >> 24) & 0xff),
         (int) ((x >> 16) & 0xff),
         (int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
    );
}
IPaddr_t string_to_ip(char *s)
{
    IPaddr_t addr;
    char *e;
    int i;

    if (s == NULL)
        return(0);

    for (addr=0, i=0; i<4; ++i) {
        ulong val = s ? simple_strtoul(s, &e, 10) : 0;
        addr <<= 8;
        addr |= (val & 0xFF);
        if (s) {
            s = (*e) ? e+1 : e;
        }
    }

    return (htonl(addr));
}



IPaddr_t getenv_IPaddr (char *var)
{
    //return (string_to_ip(getenv(var)));
    return (string_to_ip(var));
}

int main (void)
{
    unsigned long abc=0;
    char b[256];

    abc=getenv_IPaddr(CONFIG_IPADDR);

    printf("0x%lx\n", abc);

    ip_to_string(abc, b);

    printf("%s\n", b);

    return 0;
}


其中 htonl 和 ntohl 是  <arpa/inet.h>內的函數

結果:

0x1400a8c0
192.168.0.20


【轉貼】 uboot source code

沒有留言:

張貼留言