网络编程中常用的地址结构与转换(IPV4/IPv6)

来源:互联网 发布:软件历史版本下载 编辑:程序博客网 时间:2024/06/07 00:56

1. IPV4/IPV6套接字地址结构:

IPV4套接字地址结构:

#include <netinet/in.h>struct in_addr {      unsigned long s_addr;            /* 32-bit IPV4 address, network byte ordered */}; struct sockaddr_in {      short int sin_family;            /* Address family AF_INET */     unsigned short int sin_port;     /* 16-bit TCP or UDP Port Number, network byte ordered */     struct in_addr sin_addr;         /* 32-bit IPV4 address, network byte ordered */     unsigned char sin_zero[8];       /* Unused */ };

通用的套接字结构:

#include <sys/socket.h>struct sockaddr {     unsigned short sa_family;        /* address family, AF_INET/AF_ISO/AF_UNIX */    char sa_data[14];                /* 14 bytes of protocol address */};

IPV6套接字地址结构:

#include <netinet/in.h>struct in6_addr {       uint8_t s6_addr[16];          /* 128-bit IPv6 address, network byte ordered */ }; struct sockaddr_in6 {        sa_family_t sin6_family;      /* AF_INET6 */       in_port_t sin6_port;          /* transport layer port# */       uint32_t sin6_flowinfo;       /* flow information, underfined */       struct in6_addr sin6_addr;    /* IPv6 address, network byte ordered */       uint32_t sin6_scope_id;       /* set of interfaces for a scope */ };

另一个很有用的套接字地址结构:

#include <netdb.h>struct addrinfo{       int ai_flags;                 /* AI_PASSIVE,AI_CANONNAME,AI_NUMERICHOST */       int ai_family;                /* AF_INET,AF_INET6 */       int ai_socktype;              /* SOCK_STREAM,SOCK_DGRAM */       int ai_protocol;              /* IPPROTO_IP, IPPROTO_IPV4, IPPROTO_IPV6 */       size_t ai_addrlen;            /* Length */       char *ai_cannoname;          /* Canonical name for service location */       struct sockaddr *ai_addr;    /* struct sockaddr */       struct addrinfo *ai_next;     /* pNext */ };

2. 地址转换函数

IPv4中,可使用inet_ntoa/inet_aton来转化字符串形式表示的IPv4地址和数字形式表示的IPv4地址,此函数不能用于ipv6地址转换。

#include<sys/socket.h>#include<netinet/in.h>#include<arpa/inet.h>int inet_aton(const char *cp,struct in_addr *inp);char *inet_ntoa(struct in_addr in);

IPv6中,使用inet_ntop/inet_pton来转化字符串形式表示的IPv6地址和数字形式表示的IPv6地址, IPv4中也可使用这两个函数。

#include <sys/types.h>#include <sys/socket.h>#include <arpa/inet.h>int inet_pton(int af, const char *src, void *dst);const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt);

 

参考:http://www.cnblogs.com/sunada2005/archive/2013/08/06/3240724.html

0 0
原创粉丝点击