inet

    xiaoxiao2021-03-25  91

    日前在学习大神之作《Unix网络编程》,并尝试将书中代码coding并运行。

    今天仿写的是inet_ntop()函数,位于原书P61页,该函数可实现网络字节序的二进制值到点分十进制字符串的转换。

    其中,字母n代表numeric,格式存在于套接口地址结构中的二进制值;

                字母p代表presentation,格式通常是ASCII串。

       

    以下代码为inet_ntop()的简单实现及调用,且仅支持IPv4。

    运行结果例如:

    $ ./a.out 0x816fa8c0 numeric: 0x816fa8c0  presentation: 192.168.111.129 

    作为一只小小菜鸟,在学习的路上还望各位大牛多多指正

    #include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #define INET_ADDRLEN 20 const char* simplified_inet_ntop(int family, const void *addrptr, char *strptr, int len) { unsigned char temp_str[INET_ADDRLEN]; memset(temp_str, 0,INET_ADDRLEN); const unsigned char* temp_addrptr = (const unsigned char*)addrptr; if(family == AF_INET) { snprintf(temp_str, sizeof(temp_str),"%d.%d.%d.%d", *temp_addrptr,*(temp_addrptr+1),*(temp_addrptr+2),*(temp_addrptr+3)); if(strlen(temp_str) >= len) { return NULL; } else { memcpy(strptr,temp_str, strlen(temp_str)); return strptr; } } else { printf("protocol not supported!\n"); return NULL; } } int main(int argc, char *argv[]) { unsigned char str[INET_ADDRLEN]; memset(str, 0, INET_ADDRLEN); struct in_addr addr; memset(&addr, 0, sizeof(addr)); if(argc == 2) { sscanf(argv[1], "%x", &addr.s_addr); } else { printf("Usage: ./a.out 0xXXXXXXXX\r\n"); exit(1); } if(simplified_inet_ntop(AF_INET,(const void *)&addr, str, INET_ADDRLEN) == NULL) { printf("inet_ntop error for %s \r\n", argv[1]); exit(1); } else { printf("numeric: 0x%x \r\n",addr.s_addr); printf("presentation: %s \r\n",str); exit(0); } }

    转载请注明原文地址: https://ju.6miu.com/read-39922.html

    最新回复(0)