htons/htonl、ntohs/ntohl、inet_addr、inet_ntoa

1.htons/htonl

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);

两个函数都是 将无符号整型从主机字节序转换成网络字节序。
那各有什么区别呢?
htonl()表示将32位的主机字节序转化为32位的网络字节序 htons()表示将16位的主机字节顺序转化为16位的网络字节顺序。(ip地址是32位,端口号是16位)
对于端口的转换用htons(16位),如果用htonl,由于端口号是2位,那么高2位全是0,赋值后就是0;如果要转换的数据二进制超过16位,只能用htonl,如果用htons,会造成数据的丢弃。
2.ntohs/ntohl

#include <arpa/inet.h>
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

两个函数 都是 将无符号整型从网络字节序转换成主机字节序。
那各有什么区别呢?
ntohl()表示将32位数由网络字节序转换成主机字节序,返回一个以主机字节序表示的32位数;
ntohs()表示将16位数由网络字节序转换成主机字节序,返回一个以主机字节序表示的16位数。
3.inet_addr

 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <arpa/inet.h>
 in_addr_t inet_addr(const char *cp);

参数:cp:字符串,一个点分十进制的IP地址
功能:将点分十进制IP地址转换成网络字节序整型值
如:inet_addr(“192.168.0.0”); 将字符串形式IP地址转换成按网络字节序的整型值。
4.inet_ntoa

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char *inet_ntoa(struct in_addr in);

参数:struct in_addr :网络上IP地址,是一个结构体
功能:将一个十进制网络字节序转换成点分十进制IP地址
返回值:成功:返回一个字符指针,指向一个存储着点分十进制的IP地址的静态缓冲区,错误:NULL
对htons/htonl、ntohs/ntohl、inet_addr、inet_ntoa的具体应用可以参考这篇博客:/ttps://mp.csdn.net/postedit/82720870

struct sockaddr_in{
short sin_family;//AF_INET(地址族)PF_INET(协议族)

unsigned short sin_port;/*Portnumber(必须要采用网络数据格式,普通数字可以用htons()函数转换成网络数据格式的数字)*/ 

struct in_addr sin_addr;//32位IP地址

unsigned char sin_zero[8];//没有实际意义,只是为了跟SOCKADDR结构在内存中对齐*/ 
};
另外struct in_addr :
typedef uint32_t in_addr_t; 
struct in_addr
{ 
        in_addr_t s_addr;
};

猜你喜欢

转载自blog.csdn.net/sophia__yu/article/details/82827500
今日推荐