首页 > 系统服务 > 详细

Linux中ip地址结构和ip地址的转换

时间:2018-12-02 21:40:23      阅读:181      评论:0      收藏:0      [点我收藏+]

 ip地址结构

struct sockaddr_in 
{
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
    struct in_addr sin_addr;   /* internet address */
};

/* Internet address. */
struct in_addr 
{
    uint32_t       s_addr;     /* address in network byte order */
};

点分十进制ip转换:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>

int 
main()
{
    const char *ip_str = "192.168.1.1";
    //const char *ip_str = "255.255.255.255";
    //const char *ip_str = "0.0.0.0";
    struct in_addr in;
    memset(&in, 0, sizeof(struct in_addr));
    in.s_addr = inet_addr(ip_str);    
    printf("ip addr is:%u\n", in.s_addr);
    printf("ip addr is:%s\n", inet_ntoa(in));
    memset(&in, 0, sizeof(struct in_addr));
    inet_aton(ip_str, &in);
    printf("ip addr is:%s\n", inet_ntoa(in));
    return 0;
}

结果:

shelmean:[~]$ ./a.out 
ip addr is:16885952
ip addr is:192.168.1.1
ip addr is:192.168.1.1

 

技术分享图片

 

Linux中ip地址结构和ip地址的转换

原文:https://www.cnblogs.com/shelmean/p/10054809.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!