网络编程中地址格式转换(linux下)

一、地址格式转换

1、第一个函数

#include <sys/types.h>

#include <sys/socket.h>

#include <arpa/inet.h>

 

int  inet_pton(int  af ,  const  char  * src  ,void   *  dst);

(1)功能:将点分十进制格式的地址字符串转换为网络字节序整型数

(2)返回值:成功返回1,错误返回-1

(3)参数:

         ----af   :转换格式 AF_INET(IPV4)或者AF_INET6(IPV6)

        ---- src :点分格式的地址

         ----- dst:转换后的整型变量的地址

 

2、第二个函数

const char *  inet_ntop(int  af , const  void  * src ,  char * dst , socklen_t   cnt);

(1)功能:将网络字节序整型数转换为点分格式的IP地址

(2)返回值:成功返回转换后的地址,错误返回NULL

(3)参数:

         ----af   :转换格式 AF_INET(IPV4)或者AF_INET6(IPV6)

        ---- src :整型变量的地址

         ----- dst:用来存储转换后的数据的地址

        ------cnt:存储空间的大小

 

示例:

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

int main()
{
        int addrnum;
         
        char addrstring[16] = "127.0.0.1";
        printf("address in dotted-quad format is %s\n",addrstring);
        inet_pton(AF_INET,addrstring,&addrnum);
        printf("address in network byteorder integer is 0x%x\n",addrnum);
             
        char addrstring2[16] = "";
        if(inet_ntop(AF_INET,&addrnum,addrstring2,16) == NULL)
        {
                perror("inet_ntop");
        }
        printf("address in dotted - quad format is %s \n",addrstring2);

        return 0;
}   
   

运行结果:

[root@rac2 ~]# ./addrformat
address in dotted-quad format is 127.0.0.1
address in network byteorder integer is 0x100007f
address in dotted - quad format is 127.0.0.1 



 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值