1、Determine if a string is a valid IP address in C

Beej's Guide to Network Programming

2、9.14. inet_ntop(), inet_pton()

3、Program to validate an IP address

step 1) Parse string with “.” as delimiter using “strtok()” function.
e.g. ptr = strtok(str, DELIM); step 2)
……..a) If ptr contains any character which is not digit then return 0
……..b) Convert “ptr” to decimal number say ‘NUM’
……..c) If NUM is not in range of 0-255 return 0
……..d) If NUM is in range of 0-255 and ptr is non-NULL increment “dot_counter” by 1
……..e) if ptr is NULL goto step 3 else goto step 1 step 3) if dot_counter != 3 return 0 else return 1.

方法Ⅰ

// Program to check if a given string is valid IPv4 address or not
#include <stdio.h>
#include <stdlib.h>
#include <string.h> #define DELIM "." /* return 1 if string contain only digits, else return 0 */
int valid_digit(char *ip_str)
{
while (*ip_str) {
if (*ip_str >= '0' && *ip_str <= '9')
++ip_str;
else
return 0;
}
return 1;
} /* return 1 if IP string is valid, else return 0 */
/* Check whether ip_address conforms to xxx.xxx.xxx.xxx, and there are 3 dots/'.' */
/* 暫時只能檢查符合常規IP地址的字符串,比如192.168.3.100, 如果是 8、192.167.8等這種非常規的,則處理不了。 */
int is_valid_IPV4(char * ip_str)
{
int i, num, dots = 0;
char *ptr; if(ip_str == NULL)
return 0; // 15+1 can't be replace by sizeof(ip_str), as the sizeof(*ip_str) is 4.
char *tmpstr = (char *)malloc(15+1);
memset(tmpstr, 0, sizeof(tmpstr));
memcpy(tmpstr, ip_str, 15);
printf("tmpstr is %s\n", tmpstr); // See following link for strtok()
// http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok_r.html
//ptr = strtok(ip_str, DELIM);
ptr = strtok(tmpstr, DELIM); if (ptr == NULL){
free(tmpstr);
return 0;
} while (ptr) { /* after parsing string, it must contain only digits */
if (!valid_digit(ptr)){
free(tmpstr);
return 0;
} num = atoi(ptr); /* check for valid IP */
if (num >= 0 && num <= 255) {
/* parse remaining string */
ptr = strtok(NULL, DELIM);
if (ptr != NULL)
++dots;
} else{
free(tmpstr);
return 0;
}
} /* valid IP string must contain 3 dots */
if (dots != 3){
free(tmpstr);
return 0;
} free(tmpstr);
return 1;
} // Driver program to test above functions
int main()
{
char ip1[] = "128.0.0.1";
char ip2[] = "125.16.100.1";
char ip3[] = "125.512.100.1";
char ip4[] = "125.512.100.abc";
is_valid_IPV4(ip1)? printf("Valid\n"): printf("Not valid\n");
is_valid_IPV4(ip2)? printf("Valid\n"): printf("Not valid\n");
is_valid_IPV4(ip3)? printf("Valid\n"): printf("Not valid\n");
is_valid_IPV4(ip4)? printf("Valid\n"): printf("Not valid\n"); printf("ip4 is %s\n", ip4);
return 0;
}

結果是:

Valid
Valid
Not Valid
Not Valid

方法Ⅱ

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> int isValidIpAddress(char *ipAddress)
{
struct sockaddr_in sa;
/* 函數 inet_pton會同時將 ipAddress複製到 函數的第3個參數上區,格式爲 struct sock_addr_in* */
int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr)); return result != 0;
} void main()
{
char ip1[]="192.168.3.1";
char ip2[]="192.168.3.a";
char ip3[]="192.168.3";
isValidIpAddress(ip1) ? printf("Valid\n"): printf("Not valid\n");
isValidIpAddress(ip2) ? printf("Valid\n"): printf("Not valid\n");
isValidIpAddress(ip3) ? printf("Valid\n"): printf("Not valid\n"); return;
}

結果是:

Valid
Not Valid
Not Valid

IP address/地址 检查的更多相关文章

  1. 华东师大OJ:IP Address【IP地址转换】

    /*===================================== IP Address Time Limit:1000MS Memory Limit:30000KB Total Subm ...

  2. [Swift]LeetCode468. 验证IP地址 | Validate IP Address

    Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither ...

  3. lwip IP address handling 关于 IP 地址的 操作 API接口

    lwip 2.0.3  IP address handling /** * @file * IP address API (common IPv4 and IPv6) */ 1.u32_t ipadd ...

  4. [Leetcode] restore ip address 存储IP地址

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  5. How to configure a static IP address on CentOS 7(CentOS7静态IP地址设置)

    Question: On CentOS 7, I want to switch from DHCP to static IP address configuration with one of my ...

  6. [LintCode] Restore IP Address 复原IP地址

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  7. LeetCode 1108. Defanging an IP Address (IP 地址无效化)

    题目标签:String 题目给了我们一组 ip address,让我们把 . 变成 [.],这题可以用replace,但是这样做的话,好像没意义了.所以还是走一下array,具体看code. Java ...

  8. C#调用百度高精度IP定位API通过IP获取地址

    API首页:http://lbsyun.baidu.com/index.php?title=webapi/high-acc-ip 1.申请百度账号,创建应用,获取密钥(AK) http://lbsyu ...

  9. MySQL [Warning]: IP address 'xxxx' could not be resolved: Name or service not known

    MySQL的error log 出现大量的 DNS反解析错误. DNS解析是指,将 域名解析成ip地址: DNS反解析是指,将IP地址反解析成域名: Version: MySQL Community ...

随机推荐

  1. 使用ApplicationLoader中出现报错:The IPA is invalid. It does not inlude a Payload directory

    问题处理方法: 1.将achieve的.app后缀的软件包放在一个payload的文件夹中 2.压缩该文件夹,改变.zip后缀为.ipa 3.使用applicationLoader上传该文件  

  2. Android设计模式—策略模式

    1.策略模式概念 定义一系列算法,把他们独立封装起来,并且这些算法之间可以相互替换.策略模式主要是管理一堆有共性的算法,客户端可以根据需要,很快切换这些算法,并且保持可扩展性. 策略模式的本质:分离算 ...

  3. 关于STM32下载问题的简单理解

    首先STM32分为两种下载方式1.ISP(IN-SYSTEM-PROGRAMMING在线编程)  2.JTAG 这里简单谈谈对ISP下载的理解: ISP下载是51单片机,STM等单片机比较常见的一种下 ...

  4. UIDatePicker 之显示中文 年月日

    picker_start=[[UIDatePicker alloc]initWithFrame:CGRectMake(centerView.frame.size.width/-,centerView. ...

  5. MongoDB命令学习

    mongodb不像关系型数据库有很强大的GUI客户端,虽然mongodb也有,但功能和稳定性实在不敢恭维,所以操作mongodb我们大部分 都是用类似cmd命令的方式(mongodb称为shell操作 ...

  6. JS 添加千分位,测试可以使用

    JS 添加千分位,测试可以使用 <script language="javascript" type="text/javascript">funct ...

  7. 学习笔记之APACHE ANT

    http://baike.baidu.com/link?url=KkOWkH_nMVJRbd4oj-aIHMVL4HR-s7fqm3i2brUcZzBinwUXjZgzPcYIWz5qFNNvjait ...

  8. 学习笔记之SQL Programming DB2

    http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp If you intend to update a column or ...

  9. 正则表达式 之 C#后台应用

    正则表达式在.Net就是用字符串表示,这个字符串格式比较特殊,无论多么特殊,在C#语言看来都是普通的字符串,具体什么含义由Regex类内部进行语法分析. Regex 类 存在于 System.Text ...

  10. 对JavaScript对象数组按指定属性和排序方向进行排序

    引子 在以数据为中心的信息系统中,以表格形式展示数据是在常见不过的方式了.对数据进行排序是必不可少的功能.排序可以分为按单个字段排序和按多个字段不同排序方向排序.单字段排序局限性较大,不能满足用户对数 ...