Ads 468x60px

##EasyReadMore##

07 8月, 2015

[C 語言] 檢查 IPV4 格式是否正確

 

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <iostream>

using namespace std;
int if_a_string_is_a_valid_ipv4_address(const char *str)
{
    struct in_addr addr;
    int ret;
    volatile int local_errno;

    errno = 0;
    ret = inet_pton(AF_INET, str, &addr);
    local_errno = errno;
    if (ret > 0)
        printf( "\"%s\" is a valid IPv4 address\n", str);
    else if (ret < 0)
        printf("EAFNOSUPPORT: \n");
    else
        printf("\"%s\" is not a valid IPv4 address\n", str);

    return ret;
}

int main()
{
    char *pIP = "192.168.0.22";
    char *pNotIP ="192.168.0.256";
   
    if_a_string_is_a_valid_ipv4_address(pIP);
    if_a_string_is_a_valid_ipv4_address(pNotIP);
   
    return 0;
}

0 意見:

張貼留言

 
Blogger Templates