十六进制转换为点分十进制IP格式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <arpa/inet.h>

#define MAXBUF 1024

int main(int argc, char **argv) {
    struct in_addr inaddr;
    uint32_t addr;
    char buff[MAXBUF];

    if(argc!=2) {
        fprintf(stderr, "usage: %s <hex number>\n", argv[0]);
        exit(0);
    }

    sscanf(argv[1], "%x", &addr);
    inaddr.s_addr=htonl(addr);

    if(!inet_ntop(AF_INET, &inaddr, buff, MAXBUF)) {
        fprintf(stderr, "net_ntop error: %s\n", strerror(errno));
        exit(0);
    }

    printf("%s\n", buff);

    exit(0);
}

 

posted @ 2024-01-23 16:52  东宫得臣  阅读(48)  评论(0编辑  收藏  举报