码迷,mamicode.com
首页 > Web开发 > 详细

Binary Order function In Unix Network Programming

时间:2015-01-09 23:34:47      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

ByteOrder:

技术分享
 1 #include <stdio.h>
 2 
 3 int main(int argc, char**argv)
 4 {
 5     union {
 6         short s;
 7         char    c[sizeof(short)];
 8     } un;
 9     un.s = 0x0102;
10     
11     if ( sizeof(short) == 2 )
12     {
13         if ( (un.c[0] == 1) && (un.c[1] == 2) )
14         {
15             printf("big-endian\n");
16         }
17         else if( (un.c[0] == 2) && (un.c[1] == 1) )
18         {
19             printf("little-endian\n");
20         }
21         else
22         {
23             printf("unknown byte order.\n");
24         }
25     }
26     else
27     {
28         printf("unsupport.\n");
29     }
30 }
BinaryOrder.cc

网络协议必须制定一个网络字节序,在每个TCP分节中,都有16位的端口号和32位的IPv4地址。发送协议栈和接受协议栈 必须就这些多字节字段各个字节的传送顺序达成一致。

网际协议使用大端字节序来传送这些多字节整数

主机字节序--->网络字节序:

#include<netinet/in.h>

uint16_t htons(uint16_t host16bitvalue);

uint32_t htonl(uint32_t host32bitvalue);

uint16_t ntohs(uint16_t net16bitvalue);

uint32_t ntohl(uint32_t net32bitvalue);

字节操纵函数:

#include <string.h>

void *memset(void *dest, int c, size_t len);

void *memcpy(void *dest, const void *src, size_t nbytes);

int memcmp(const void *ptr1, const void *ptr2, size_t nbytes);

ASCII 字符串---> 网络字节序的二进制值(存放在套接字地址结构中的值)之间 转换网际地址。

 

#include <arpa/inet.h>

int inet_aton( const char *strPtr, struct in_addr *addrPtr);

          /** 返回: 如字符串有效则为1,否则为0**/

in_addr_t inet_addr(const char* strPtr);

          /** 返回: 若字符串有效则为32位二进制网络字节序的IPv4地址, 否则为INADDR_NONE

char *inet_ntoa( struct in_addr inaddr);

          /**返回: 指向一个点分十进制数串的指针**/

int inet_pton( int family, const char *strPtr, void *addrPtr);

          /**若成功则为1, 若输入不是有效的表达格式则为0, 如出错则为-1**/

const char *inet_ntop( int family, const void *addrPtr, char *strPtr, size_t len);

          /**返回:若陈宫则为指向结果的指针,若出错则为NULL**/

1 struct sockaddr_in addr;
2 inet_ntop(AF_INET, &addr.sin_addr, str, sizeof(str));
3 
4 struct sockaddr_in6 addr6;
5 inet_ntop(AF_INET6, &addr6.sin6_addr, str, sizeof(str));

 

Binary Order function In Unix Network Programming

标签:

原文地址:http://www.cnblogs.com/shidabao/p/4214236.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!