htons(), ntohs(),htonl(),ntohl(), inet_addr() ,inet_ntoa() || bzero()

来源:互联网 发布:苹果淘宝直播怎么加入 编辑:程序博客网 时间:2024/06/05 12:40
  1. htonl() , ntohl() ,htons(),ntohs()
#include <netinet/in.h>uint32_t htonl(uint32_t hostlong);uint16_t htons(uint16_t hostshort);uint32_t ntohl(uint32_t netlong);uint16_t ntohs(uint16_t netshort);htonl() :“Host to Network Long int32Bytesntohl() :“Network to Host  Long int32Byteshtons():“Host to Network Short int16Bytesntohs():“Network to Host Short int16Bytes

网络字节顺序NBO(Netwoork Byte Order):按从高到低的顺序存储
主机字节顺序HBO(Host Byte Order):不同的CPU,存储方式不同

2 inet_addr() , inet_ntoa(),inet_aton()

#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>// ALL THESE ARE DEPRECATED!  Use inet_pton()  or inet_ntop() instead!!char *inet_ntoa(struct in_addr in);int inet_aton(const char *cp, struct in_addr *inp);in_addr_t inet_addr(const char *cp);struct sockaddr_in antelope;char *some_addr;inet_aton("10.0.0.1", &antelope.sin_addr); // store IP in antelopesome_addr = inet_ntoa(antelope.sin_addr); // return the IPprintf("%s\n", some_addr); // prints "10.0.0.1"// and this call is the same as the inet_aton() call, above:antelope.sin_addr.s_addr = inet_addr("10.0.0.1");

inet_aton()将strptr所指的字符串转换位32位网络字节序二进制,并有addptr指针来存储,返回值位1表示成功,为0表示失败。

inet_addr()返回转换后的32位网络字节序二进制,返回的IP地址为0.0.0.0到255.255.255.255,如果函数出错,返回INADDR_NONE,意味着点分二进制数串255.255.255.255不能由此函数处理。

inet_ntoa()将一个32位的网络字节序二进制IPV4地址转换为相应的点分十进制数串。

inet_pton()和inet_ntop()对IPv4和IPv6地址都能进行处理,p表示presentation,字母n代表numeric

#include <arpa/inet.h>const char *inet_ntop(int af, const void *src,                      char *dst, socklen_t size);int inet_pton(int af, const char *src, void *dst);// IPv4 demo of inet_ntop() and inet_pton()struct sockaddr_in sa;char str[INET_ADDRSTRLEN];// store this IP address in sa:inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));// now get it back and print itinet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);printf("%s\n", str); // prints "192.0.2.33"

/若函数成功,则返回1,若输入不是有效的格式,则函数返回0,;若处理失败,函数返回-1 /
int inet_pton(int family,const char * strptr,void * addrptr);

/若函数处理成功,返回指向结果的指针,若失败,返回NULL /
const char* inet_ntop(int family, const void* addrptr, char* strptr,size_t len);

inet_pton()转换strptr指针指向的串,并通过addrptr存储二进制结果。
inet_ntop()从二进制数值格式addrptr字符串到转换为点分十进制字符串strptr,参数len是目标的大小,以免函数出现溢出
inet_pton()则是将点分十进制字符串strptr转换为二进制形式的字符串。

  1. 列表内容
    bzero():将内存(字符串)前n个字节清零
    void bzero(void* s,int n)
    等价于memset((void*)s,0,size_t n),用来将内存块的前n个字节清零。
原创粉丝点击