Maxbad`Blog

整数转IP地址

2021-05-24 · 1 min read

这个例子很巧妙的利用了联合体共享内存的特点。

union IPNode
{
  unsigned int addr;
  struct
  {
    unsigned char s4,s3,s2,s1;
  };
};

void PrintIP(unsigned int x)
{
  IPNode a;
  a.addr = x;
  printf("%d.%d.%d.%d\n",a.s1,a.s2,a.s3,a.s4);
}

void main()
{
  unsigned int ip = 1567898765;// "192.11.23.22"
  PrintIP(ip);
}

IP文本转整数

uint32_t ip2long( char* addr )
{
    uint32_t c, octet, t;
    uint32_t ipnum;
    int i = 3;
    octet = ipnum = 0;
    while ( ( c = *addr++ ) ) {
        if ( c == '.' ) {
            ipnum <<= 8;
            ipnum += octet;
            i--;
            octet = 0;
        } else {
            t = octet;
            octet <<= 3;
            octet += t;
            octet += t;
            c -= '0';
            octet += c;
        }
    }
    ipnum <<= 8;
    return ipnum + octet;
}