inet相关函数

2021-04-02, updated 2021-09-12

inet_pton - convert IPv4 and IPv6 addresses from text to binary form

#include <arpa/inet.h>

int inet_pton(int af, const char *restrict src, void *restrict dst);

参数

返回值

inet_pton() returns 1 on success (network address was successfully converted). 0 is returned if src does not contain a character string representing a valid network address in the specified address family. If af does not contain a valid address family, -1 is returned and errno is set to EAFNOSUPPORT.

示例

#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <sys/types.h>         /* See NOTES */
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#define NS_INADDRSZ 4

static int my_inet_pton4(src, dst)
    const char *src;
    u_char *dst;
{
    int saw_digit, octets, ch;
    u_char tmp[NS_INADDRSZ], *tp;

    saw_digit = 0;
    octets = 0;
    *(tp = tmp) = 0;
    while ((ch = *src++) != '\0') {

        printf("ch:%c\n", ch);
        if (ch >= '0' && ch <= '9') {
            u_int new = *tp * 10 + (ch - '0');

#if 1
            printf("saw_digit:%d *tp:%d \n", saw_digit, *tp);
            if (saw_digit && *tp == 0) {
                printf("saw_digit:%d *tp:%d \n", saw_digit, *tp);
                return (0);
            }
#endif
            if (new > 255) {
                return (0);
            }
            *tp = new;
            if (! saw_digit) {
                if (++octets > 4) {
                    return (0);
                }
                saw_digit = 1;
            }
        } else if (ch == '.' && saw_digit) {
            if (octets == 4) {
                return (0);
            }
            *++tp = 0;
            saw_digit = 0;
        } else {
            return (0);
        }
    }
    if (octets < 4) {
        return (0);
    }
    memcpy(dst, tmp, NS_INADDRSZ);
    return (1);
}

int main()
{
    int gw_ip = 0;
    struct in_addr addr;;
    char temp_buf[512]={0};
    int wan_mode = 0;

    memset(&addr,0,sizeof(struct in_addr));
    printf("%d\n", inet_pton(AF_INET, "192.168.44.1", &addr));
    // printf("%d\n", my_inet_pton4("192.168.01.1", &addr));
    printf("%x\n", addr.s_addr);
    gw_ip = ntohl(addr.s_addr);
    printf("%x\n", gw_ip);
    return 0;
}

问题:

glibc中不能处理192.168.044.1,uclib 中可以正常处理

words: 324 tags: c