问题
有一个IP地址"127.0.0.1" 需要他的四字节整型值?
反过来有一个整型值,如何转换为一个点分十进制的IP地址?
其实libc是提供这个接口的,不需要自己再造轮子,对比我们自己的实现,用到了联合体,非常值得学习,如下:
1、inet_addr
typedef uint32_t in_addr_t;
struct in_addr
{
in_addr_t s_addr;
};
/*
* Ascii internet address interpretation routine.
* The value returned is in network order.
*/
in_addr_t
__inet_addr(const char *cp) {
struct in_addr val;
if (__inet_aton(cp, &val))
return (val.s_addr);
return (INADDR_NONE);
}
weak_alias (__inet_addr, inet_addr)
/*
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*/
int
__inet_aton(const char *cp, struct in_addr *addr)
{
static const in_addr_t max[4] = {
0xffffffff, 0xffffff, 0xffff, 0xff };

2475

被折叠的 条评论
为什么被折叠?



