Determines whether the string is an IP address.

Source: Internet
Author: User

Determines whether the string is an IP address.

Method 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_1_4_address (const char * Str)

{

Struct in_addr ADDR;

Int ret;

Ret = inet_ton (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_ton (INT family, const char * strptr, void * addrptr );

Return Value: 1-success; 0-the input is not a valid expression format;-1-error.

Method 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

& Amp; 0 & amp; = C & amp; 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 );

}

}

Original

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.