xxyyzz886 2018-11-18 09:02 采纳率: 50%

# 【C++】一个字符串分解问题

TragetToIpAndProt(http://www.xxx.com:80|http://www.yyy.com:88)

 int   iNum = 0;
unsigned long uip[100];
u_short DProt[100];

unsigned long ResolvDNS(char *szTarget)
{
long i;
struct hostent *he;

if((he=gethostbyname(szTarget))==NULL)
return(0);
else

return(i);
}

void TragetToIpAndProt(char *ip/*,ULONG *pip,DWORD *pProt,int icount*/)
{
//初始化SOCK_RAW
return;
}
char ipTemp[64] = {"0"};
char chip[32] = {"0"},chprot[32] = {"0"};
char *ptr = NULL,*ptr2 = NULL;

while(*ip)
{
if (strstr(ip,"|") != NULL)  //如果找到分隔符说明多个目标
{
int len = strcspn(ip,"|");
strncpy(ipTemp,ip,len);    //分解出其中一个IP

if (strstr(ipTemp,":") != NULL)  //有端口
{
ptr = ipTemp;
strncpy(chip,ptr,strcspn(ip,":"));
ptr += strcspn(ip,":") + 1;
strcpy(chprot,ptr);
uip[iNum] = ResolvDNS(chip);
DProt[iNum] = htons(atoi(chprot));
}else
{
uip[iNum] = ResolvDNS(ipTemp);
DProt[iNum] = 0;
}
ip += strlen(ipTemp) + 1;
}else                      //最后一个目标了
{
strcpy(ipTemp,ip);
if (strstr(ipTemp,":") != NULL)
{
ptr2 = ipTemp;
strncpy(chip,ptr2,strcspn(ptr2,":"));
ptr2 += strcspn(ptr2,":") +1;
strcpy(chprot,ptr2);
uip[iNum] = ResolvDNS(chip);
DProt[iNum] = htons(atoi(chprot));
}else
{
uip[iNum] = ResolvDNS(ip);
DProt[iNum] = 0;
}
ip += strlen(ipTemp);
}

memset(ipTemp,0,sizeof(ipTemp));
memset(chip,0,sizeof(chip));
memset(chprot,0,sizeof(chprot));
iNum++;
}

}

• 写回答

#### 2条回答默认 最新

• 任飘萍 2018-11-20 08:35
关注

# 根据你的要求, 修改了uip的类型, 和TragetToIpAndProt函数按":"拆分的地方, 下面附上代码和执行结果

int iNum = 0;
char uip[100][32];
u_short DProt[100];

void TragetToIpAndProt(char *ip)
{

char ipTemp[64] = {"0"};
char chip[32] = {"0"},chprot[32] = {"0"};
char *ptr = NULL,*ptr2 = NULL;

while(*ip)
{
if (strstr(ip,"|") != NULL)  //如果找到分隔符说明多个目标
{
int len = strcspn(ip,"|");
strncpy(ipTemp,ip,len);    //分解出其中一个IP

if ((ptr = strrchr(ipTemp,':')) != NULL && (ptr - ipTemp) != 4)  //有端口
{
strncpy(chip,ipTemp,ptr-ipTemp);
ptr += 1;
strcpy(chprot,ptr);
strcpy(uip[iNum],chip);
//uip[iNum] = ResolvDNS(chip);
DProt[iNum] = atoi(chprot);
}else
{
strcpy(uip[iNum],ipTemp);
//ip[iNum] = ResolvDNS(ipTemp);
DProt[iNum] = 0;
}
ip += strlen(ipTemp) + 1;
}else                      //最后一个目标了
{
strcpy(ipTemp,ip);
if ((ptr2 = strrchr(ipTemp,':')) != NULL && (ptr2 - ipTemp) != 4)
{
strncpy(chip,ipTemp,ptr2-ipTemp);
ptr2 += 1;
strcpy(chprot,ptr2);
strcpy(uip[iNum],chip);
//uip[iNum] = ResolvDNS(chip);
DProt[iNum] = atoi(chprot);
}else
{
strcpy(uip[iNum],ipTemp);
//uip[iNum] = ResolvDNS(ip);
DProt[iNum] = 0;
}
ip += strlen(ipTemp);
}

memset(ipTemp,0,sizeof(ipTemp));
memset(chip,0,sizeof(chip));
memset(chprot,0,sizeof(chprot));
iNum++;
}

}

int main(int argc, char* argv[])
{
char *str = "http://www.xxx.com|http://www.yyy.com:88";
TragetToIpAndProt(str);

printf("%s:%d\n%s:%d\n", uip[0], DProt[0], uip[1], DProt[1]);

system("pause");
return 0;
}



本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 自己配的nginx 正向代理一直失败（相关搜索：谷歌浏览器|拒绝连接）