您的位置:首页 > 其它

C判断一字符串是否是合法的IP地址

2012-03-01 15:39 267 查看
C判断一字符串是否是合法的IP地址

方法1: 判断各个部分是否合法

int is_valid_ip(const char *ip_str)

{

unsigned int n1,n2,n3,n4;

if(sscanf(ip_str, "%u.%u.%u.%u", &n1, &n2, &n3, &n4) != 4)

{

return 0;

}

if( (n1 != 0) && (n1 <= 255) && (n2 <= 255) && (n3 <= 255) && (n4 <= 255) )

{

char buf[64];

sprintf(buf, "%u.%u.%u.%u", n1, n2, n3, n4);

if(strcmp(buf, ip_str))

{

return 0;}return 1;

 }

return 0;

}

方法2: 使用函数
inet_pton()

#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h>

int is_valid_ip (const char *ip_str)

{

struct sockaddr_in sa;

int result = inet_pton(AF_INET, ip_str, &(sa.sin_addr));

if (result == 0)

{return result; 

}

return 1;

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: