字节序和IP地址转换

网络中传输的数据必须使用网络字节序,即大端字节序

小端字节序(little-endian) - 低序字节存储在低地址 (主机字节序)

大端字节序(big-endian)- 高序字节存储在低地址 (网络字节序)

可以通过以下方法判断当前主机的字节序

#include<stdio.h>//指针强转
int main(int argc, char const *argv[])
{
    int a=0x12345678;
    char b;
    b=(char)a;
    printf("%#x %#x\n",a,b);
    return 0;
}

#include<stdio.h>//数据类型强转
int main(int argc, char const *argv[])
{
    int a=0x12345678;
    printf("%#x %#x\n",(char)a,(short)a);
    return 0;
}

#include <stdio.h>//共用体

union un {
    int a;
    short b;
    char c;
};

int main(int argc, char const *argv[])
{
    union un st;
    st.a=0x12345678;
    printf("%#x %#x\n",st.b,st.c);
    return 0;
}

主机字节序到网络字节序转换
u_long htonl (u_long hostlong);
u_short htons (u_short short);

主机字节序到网络字节序转换

u_long ntohl (u_long hostlong);
u_short ntohs (u_short short);

IP地址转换

typedef uint32_t in_addr_t;
struct in_addr {
    in_addr_t s_addr;
};

in_addr_t inet_addr(const char *cp);  //从人看的ip地址转为机器使用的32位无符号整数
char *inet_ntoa(struct in_addr in);  //从机器到人

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值