首先先看一下判断字符串是否为IP地址(IPv4地址是否合法)
的方法:
(【C语言】判断字符串是否为IP地址(IPv4地址是否合法))
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/**
* @brief 判断IPv4地址是否合法
* @param ip: 待校验的ip地址
* @return true: 校验成功 false:校验失败(IP地址不合法)
* @author PJW
*/
bool IPv4_verify(char *ip) {
int a,b,c,d;
char t;
if (4 == sscanf(ip,"%d.%d.%d.%d%c",&a,&b,&c,&d,&t)){
if (0<=a && a<=255
&& 0<=b && b<=255
&& 0<=c && c<=255
&& 0<=d && d<=255) {
return true;
}
}
return false;
}
void main() {
char ip[50]="192.1.2.3.4567";
// char ip[50]="192.1.2.3";
bool res = IPv4_verify(ip);
if(true == res){
printf("[%s] is valid IPv4\n", ip);
}else{
printf("[%s] is invalid IPv4\n", ip);
}
}
执行结果:
然后根据以上方法,修改为从一个复杂的字符串中提取出IPv4
地址:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/**
* @brief IPv4地址提取
* @param str: 待提取的字符串
* @param len: 待提取的字符串长度
* @param out_ip: 提取到的 IPv4 地址
* @return true: 提取成功
* false:提取失败(IP地址不存在或不合法)
* @author PJW
* @date 2021/07/01
*/
bool IPv4_GET(char *str,int len,char *out_ip) {
int a,b,c,d;
char *p = str;
for(int i=0;i<len;i++){
if((*p >= '0')&&(*p <= '9')){
if(4 == sscanf(p,"%d.%d.%d.%d",&a,&b,&c,&d)){
if (0<=a && a<=255
&& 0<=b && b<=255
&& 0<=c && c<=255
&& 0<=d && d<=255) {
sprintf(out_ip,"%d.%d.%d.%d\n",a,b,c,d);
// printf("IPv4: %d.%d.%d.%d\n",a,b,c,d);
return true;
}
}
}
p++;
}
return false;
}
void main() {
char str[50]="+QIACT: 1,1,1,\"10.5.110.126\"";
char ip[16]={0};
bool res = IPv4_GET(str, strlen(str), ip);
if(true == res){
printf("Get a valid IPv4 address: %s\n", ip);
}else{
printf("No valid IPv4 address was obtained\n");
}
}
执行结果: