主机序和网络序转换

主机序和网络序

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
", *(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
", 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
", *(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
", ip);

# ./a.out 
ip: 127.0.0.1
原文地址:https://www.cnblogs.com/zhangxuechao/p/11709698.html