主机序和网络序转换

主机序和网络序

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

网络序和点分十进制

int inet_aton(const char *cp, struct in_addr *inp);
char *inet_ntoa(struct in_addr in);
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);

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

af:AF_INET、AF_INET6

inet_aton

char *ip = "127.0.0.1";

struct in_addr in = {0};
inet_aton(ip, &in);
printf("in_addr: %x\n", *(unsigned int*)&in);

# ./a.out
in_addr: 100007f

inet_ntoa

uint32_t addr = 0x100007f;
char *ip = inet_ntoa(*(struct in_addr*)&addr);
printf("ip: %s\n", ip);

# ./a.out 
ip: 127.0.0.1

inet_pton

char *ip = "127.0.0.1";
struct in_addr in = {0};
inet_pton(AF_INET, ip, (void*)&in);
printf("in_addr: %x\n", *(unsigned int*)&in);

# ./a.out
in_addr: 100007f

inet_ntop

uint32_t addr = 0x100007f;
char ip[20] = {0};
inet_ntop(AF_INET, (void*)&addr, ip, sizeof(ip));
printf("ip: %s\n", ip);

# ./a.out 
ip: 127.0.0.1
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值