#ifdef __OPTIMIZE__
/* We can optimize calls to the conversion functions. Either nothing has
to be done or we are using directly the byte-swapping functions which
often can be inlined. */
# if __BYTE_ORDER == __BIG_ENDIAN
/* The host byte order is the same as network byte order,
so these functions are all just identity. */
# define ntohl(x) (x)
# define ntohs(x) (x)
# define htonl(x) (x)
# define htons(x) (x)
# else
# if __BYTE_ORDER == __LITTLE_ENDIAN
# define ntohl(x) __bswap_32 (x)
# define ntohs(x) __bswap_16 (x)
# define htonl(x) __bswap_32 (x)
# define htons(x) __bswap_16 (x)
# endif
# endif
#endif
如果主机系统的字节序为大端模式,这些函数定义为空,在进行socket编程的时候,为了提高代码的可移植性,应该总是使用这些函数进行主机字节序和网络字节序的处理;
函数使用举例:
#include
#include
int main(int argc,char **argv)
{
int value1 = 0x12345678; //定义一个4字节的数据
short int value2 = 0x1234; //定义一个2字节的数据
printf("htonl(0x%08x) = 0x%08x\r\n",value1,htonl(value1));
printf("htons(0x%04x) = 0x%04x\r\n",value2,htons(value2));
}
代码执行如下:
地址转换函数
使用协议无关性的两个地址处理函数,函数如下:
#include
//返回:若成功返回1,若输入不是有效的表达格式返回0,出错返回-1
int inet_pton(int family,const char *strptr, void *addrptr);