网络字节序和主机字节序相互转换函数

来源:互联网 发布:网络粪坑 编辑:程序博客网 时间:2024/05/22 12:58
#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

0 0