首页 > 其他分享 >网络字节与主机节序的转换函数实践

网络字节与主机节序的转换函数实践

时间:2022-10-07 18:23:48浏览次数:80  
标签:const 字节 主机 void 节序 addrptr inet strptr

#include <netinet/in.h>
unit16_t htons(uint16_t host16bitvalue);
uint32_t htonl(uint32_t host32bitvalue); //均返回网络字节序的值
unit16_t ntohs(uint16_t net16bitvalue);
uint32_t ntohl(uint32_t net32bitvalue); //均返回主机字节序的值

h代表host,n代表network,s代表short,l代表long。如果长整型占用64位,htonl和ntohl操作的仍然是32位的值。

源自berkeley的字节操纵函数:

#include <string.h>
void bzero(void *dest, size_t nbytes);
void bcopy(const void *src, void *dest, size_t nbytes);
int bcmp(const void *ptr1, const void *ptr2, size_t nbytes);

 

地址转换函数:

#include <arpa/inet.h>
int inet_aton(const char *strptr, struct in_addr *addrptr);
in_addr_t inet_addr(const char *strptr);
char* inet_ntoa(struct in_addr inaddr);

inet_aton将strptr所指c字符串转换成一个32位的网络字节序二进制值,并通过addrptr指针来存储。成功返回1,否则返回0.

inet_ntoa将一个32位的网络字节序二进制IPV4地址转换成相应的点分十进制数串。由于返回值所指向的字符串驻留在静态内存中,所以该函数是不可重入的。

#include <arpa/inet.h>
int inet_pton(int family, const char* strptr, void *addrptr);
const char* inet_ntop(int family, const void* addrptr, char* strptr, size_t len);

 

这两个函数的family参数可以是AF_INET、AF_INET6。如果以不支持的地址族作为这个参数,返回一个错误,erron置为EAFNOSUPPORT。

inet_pton尝试转换strptr所指字符串,并将二进制结果存放在addrptr中,成功返回1,失败返回0.

inet_ntop进行相反的转换,从数值格式(addrptr)转换到表达格式(strptr)。len参数是目标存储单元的大小,以免溢出其调用者的缓冲区。调用陈宫时strptr就是这个函数的返回值

一般有如下定义:

#include<netinet/in.h>
#define INET_ADDRSTRLEN 16 //for IPv4 dotted-decimal
#define INET6_ADDRSTRLEN 46 //for IPv6 hex string

标签:const,字节,主机,void,节序,addrptr,inet,strptr
From: https://www.cnblogs.com/frizenors/p/16760212.html

相关文章