C/C++程序开发(07):点分十进制表示的IP地址解析方法

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include <iostream>
#include <cassert>
using namespace std;


const int maxHostLen = 10;
const int ipCount = 4;


//函数功能:给定元素个数,创建字符串数组
//参数:elementCount 数组元素个数
//参数:element 每个数组元素的长度
//返回值:返回一个包含elementeredCount个长度为elementLen的字符串数组
char** mallocChar(int elementCount, int elementLen)
{
char** hostInfo = new char*[elementCount];
for (int i = 0; i < elementCount; i++)
{
hostInfo[i] = new char[elementLen];
memset(hostInfo[i], 0, sizeof(char)* elementLen);
}
return hostInfo;
}
//功能:动态分配内存字符串数组释放
//参数:freeChar 要释放的字符串数组
//参数:elementCount 字符串数组元素个数
void freeChar(char** freeChar, int elementCount)
{
for (int i = 0; i < elementCount; i++)
{
if (freeChar[i])
{
delete freeChar[i];
freeChar[i] = NULL;
}
}
if (freeChar)
{
delete[] freeChar;
freeChar = NULL;
}
}
//功能:从给定的ip地址中解析点分字符串
//参数:ipAddr 要解析的ip地址
//参数:hostInfo 保存解析结果
//返回值:解析成功返回TRUE,失败返回False
bool findCstyle(char* ipAddr, char**& hostInfo)
{

int itertmp = 0;
char* tmp1 = ipAddr;
char* tmp2 = ipAddr;


while (*tmp1)
{
tmp1++;
if (*tmp1 == '.'|| *tmp1 == '\0')
{
strncpy(hostInfo[itertmp], tmp2, tmp1 - tmp2);
tmp2 = tmp1 + 1;
itertmp++;
}
}
if (hostInfo)
{
return true;
}
return false;
}
//功能:单一字符串数组
//参数:hostInfo 要打印的字符串数组
//参数:element 字符串数组中的元素个数
void print(char** hostInfo, int elementCount)
{
for (int i = 0; i < elementCount; i++)
{
printf("%s\n", hostInfo[i]);
}
}


void findCppStyle()
{
cout << "input your ip address:" << endl;
string address;
cin >> address;
string block1, block2, block3, block4;
int dot1 = address.find(".", 0);
assert(dot1 != string::npos);
block1 = address.substr(0, dot1);
//find函数的功能是从string中寻找指定字符,找到则返回该字符地址
int dot2 = address.find(".", dot1 + 1);
//string::npos表示到达字符串的尾部
assert(dot2 != string::npos);
block2 = address.substr(dot1 + 1, dot2 - dot1 - 1);


int dot3 = address.find(".", dot2 + 1);
assert(dot3 != string::npos);
block3 = address.substr(dot2 + 1, dot3 - dot2 - 1);


assert(address.find(".", dot3 + 1) == string::npos);
block4 = address.substr(dot3 + 1, address.size() - dot3 - 1);


cout << block1 << endl;
cout << block2 << endl;
cout << block3 << endl;
cout << block4 << endl;
}


int main()
{
findCppStyle();
char ip[35] = { 0 };
printf("input your ip address:");
scanf("%s", ip);
char** hostInfo = mallocChar(ipCount, maxHostLen);
if (findCstyle(ip, hostInfo))
{
printf("output is :\n");
print(hostInfo, ipCount);
}
else
{
printf("fail\n");
}
freeChar(hostInfo, ipCount);
return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小薛引路

喜欢的读者,可以打赏鼓励一下

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值