Integer to IP Address - C

后端 未结 9 758
陌清茗
陌清茗 2020-12-07 17:45

I\'m preparing for a quiz, and I have a strong suspicion I may be tasked with implementing such a function. Basically, given an IP address in network notation, how can we ge

9条回答
  •  北海茫月
    2020-12-07 18:25

    This is what I would do if passed a string buffer to fill and I knew the buffer was big enough (ie at least 16 characters long):

    sprintf(buffer, "%d.%d.%d.%d",
      (ip >> 24) & 0xFF,
      (ip >> 16) & 0xFF,
      (ip >>  8) & 0xFF,
      (ip      ) & 0xFF);
    

    This would be slightly faster than creating a byte array first, and I think it is more readable. I would normally use snprintf, but IP addresses can't be more than 16 characters long including the terminating null.

    Alternatively if I was asked for a function returning a char*:

    char* IPAddressToString(int ip)
    {
      char[] result = new char[16];
    
      sprintf(result, "%d.%d.%d.%d",
        (ip >> 24) & 0xFF,
        (ip >> 16) & 0xFF,
        (ip >>  8) & 0xFF,
        (ip      ) & 0xFF);
    
      return result;
    }
    

提交回复
热议问题