c++ ip地址和int类型的相互转换

int Int2Ip(UINT uiIp, string& strOut)
{
  strOut.clear();
  BYTE bN1 = 0, bN2 = 0, bN3 = 0, bN4 = 0;
  char arrIp[32] = { 0 };
  bN1 = (uiIp)& 0xFF;
  bN2 = (uiIp >> 8) & 0xFF;
  bN3 = (uiIp >> 16) & 0xFF;
  bN4 = (uiIp >> 24) & 0xFF;
  sprintf_s(arrIp, sizeof(arrIp), "%d.%d.%d.%d", bN1, bN2, bN3, bN4);
  strOut.assign(arrIp);
  return TRUE;
}

 

int ip2int(char* ipStr, UINT& ipInt)
{
  if (ipStr == NULL) { return FALSE; }
  ipInt = 0;
  int tokenInt = 0;
  char* token = NULL;
  token = strtok(ipStr, ".");
  int i = 3;
  while (token != NULL) {
    tokenInt = atoi(token);
    ipInt += tokenInt * pow(256, i);
    token = strtok(NULL, ".");
    i--;
  }
  if (i != 0) { return FALSE; }
  return TRUE;
}

posted @ 2020-10-27 21:40  龙马8586  阅读(1139)  评论(0编辑  收藏  举报