生活随笔
收集整理的這篇文章主要介紹了
inet_ntop函数的简单实现及调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
日前在學習大神之作《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 20const 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);}
}
總結
以上是生活随笔為你收集整理的inet_ntop函数的简单实现及调用的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。