inet_ntoa() inet_aton()

int inet_aton(const char *cp, struct in_addr *inp);

将形如“192.168.1.1"类型的点分十进制ip转换成二进制,并存放在struct in_addr中

192 = 0xc0

168 = 0xa8

1 = 0x01

因此转换后的值为0xc0a811

 

char *inet_ntoa(struct in_addr in);

将二进制的ip转成点分十进制形式,转换结果作为返回值

 struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type);

将32位的二进制ip转换成一个结构体指针

 

struct hostent
{
  char *h_name;            /* Official name of host.  */
  char **h_aliases;        /* Alias list.  */
  int h_addrtype;        /* Host address type.  */
  int h_length;            /* Length of address.  */
  char **h_addr_list;        /* List of addresses from name server.  */
#ifdef __USE_MISC
# define    h_addr    h_addr_list[0] /* Address, for backward compatibility.*/
#endif
};

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

 

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>

int main(int argc, char** argv)
{

    struct in_addr addr;
    struct hostent *host;
    char ** var;

    if(argc < 2)
    {
        printf("usage: %s | ip\n", *argv);
        exit(1);
    }

    argv++;

    for(; *argv!=NULL; argv++)
    {
        if(inet_aton(*argv, &addr) != 0)
        {
            host = gethostbyaddr(&addr, 4, AF_INET);
            printf("ip address: %s\n", *argv);
        }

        if(host == NULL)
        {
            fprintf(stderr, "no ip address: %s\n", argv[1]);
            continue;
        }
        else
        {
            printf("host name: %s\n", host->h_name);

            for(var=host->h_addr_list; *var!=NULL; var++)
            {
                printf("inet_ntoa ip address: %s\n", inet_ntoa(*(struct in_addr*)(*var)));
            }
        }


    }


    return 0;
}

输出结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值