Determine if a string is a valid IPv4 address in C

后端 未结 15 2056
感情败类
感情败类 2020-12-24 08:22

What would be a good way to determine if a string contains an IPv4 address? Should I use isdigit()?

15条回答
  •  醉话见心
    2020-12-24 08:47

    I asked a similar question for C++. You should be able to use a slightly modified (for C) version of what I came up with back then.

    bool isValidIpAddress(char *ipAddress)
    {
        struct sockaddr_in sa;
        int result = inet_pton(AF_INET, ipAddress, &(sa.sin_addr));
        return result != 0;
    }
    

    You'll need to #include to use the inet_pton() function.

    Update based on comments to the question: If you want to know if a C-style string contains an IP address, then you should combine the two answers given so far. Use a regular expression to find patterns that roughly match an IP address, then use the function above to check the match to see if it's the real deal.

提交回复
热议问题