判断字符串是否为ip

判断字符串是否为ip

1

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <errno.h>

int if_a_string_is_a_valid_ipv4_address(const char *str)

{

struct in_addr addr;

int ret;

ret = inet_pton(AF_INET, str, &addr);

if (ret > 0)

fprintf(stderr, "\"%s\" is a valid IPv4 address\n", str);

else if (ret < 0)

fprintf(stderr, "EAFNOSUPPORT: %s\n", strerror(errno));

else

fprintf(stderr, "\"%s\" is not a valid IPv4 address\n", str);

return ret;

}

int inet_pton(int family, const char *strptr, void *addrptr);

返回:1—成功;0—输入不是有效的表达格式,-1—出错。

2

#include <stdio.h>

#include <string.h>

int a,b,c,d;

char t;

char s[100];

void main() {

strcpy(s,"123.1.2.3.1111");

if (4==sscanf(s,"%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) {

printf("[%s] is valid IPv4\n",s);

} else {

printf("[%s] is invalid IPv4\n",s);

}

} else {

printf("[%s] is invalid IPv4\n",s);

}

}

原文

http://bbs.chinaunix.net/thread-928835-1-1.html

http://www.cnblogs.com/riky/archive/2006/11/24/570713.aspx

http://bbs.csdn.net/topics/330230349

posted @ 2013-06-02 20:36  浪里飞  阅读(498)  评论(0编辑  收藏  举报