UNP学习笔记(1)-Sockets Introduction:Socket Address Structure

  1. 1、IPv4 Socket Address Structure
  2. struct in_addr {
      in_addr_t   s_addr;           /* 32-bit IPv4 address */
                                    /* network byte ordered */
    };
    
    struct sockaddr_in {
      uint8_t         sin_len;      /* length of structure (16) */
      sa_family_t     sin_family;   /* AF_INET */
      in_port_t       sin_port;     /* 16-bit TCP or UDP port number */
                                    /* network byte ordered */
      struct in_addr  sin_addr;     /* 32-bit IPv4 address */
                                    /* network byte ordered */
      char            sin_zero[8];  /* unused */
    };
    定义在:<netinet/in.h>
    2、Generic Socket Address Structure
    struct sockaddr {
      uint8_t      sa_len;
      sa_family_t  sa_family;    /* address family: AF_xxx value */
      char         sa_data[14];  /* protocol-specific address */
    };
    定义在:<sys/socket.h>
    这个结构是通用的,符合ANSI C,所以socket函数都使用此结构作为参数进行传递。比如:
  1. int bind(int, struct sockaddr *, socklen_t);
  2. 故在使用IPv4 Socket Address Structure时,就会有以下的转换:
  3. struct sockaddr_in  serv;      /* IPv4 socket address structure */
    
    /* fill in serv{} */
    
    bind(sockfd, (struct sockaddr *) &serv, sizeof(serv));
    3、IPv6 Socket Address Structure

  4. struct in6_addr {
      uint8_t  s6_addr[16];          /* 128-bit IPv6 address */
                                     /* network byte ordered */
    };
    
    #define SIN6_LEN      /* required for compile-time tests */
    
    struct sockaddr_in6 {
      uint8_t         sin6_len;      /* length of this struct (28) */
      sa_family_t     sin6_family;   /* AF_INET6 */
      in_port_t       sin6_port;     /* transport layer port# */
                                     /* network byte ordered */
      uint32_t        sin6_flowinfo; /* flow information, undefined */
      struct in6_addr sin6_addr;     /* IPv6 address */
                                     /* network byte ordered */
      uint32_t        sin6_scope_id; /* set of interfaces for a scope */
    };
    4、New Generic Socket Address Structure
    struct sockaddr_storage {
      uint8_t      ss_len;       /* length of this struct (implementation dependent) */
      sa_family_t  ss_family;    /* address family: AF_xxx value */
      /* implementation-dependent elements to provide:
       * a) alignment sufficient to fulfill the alignment requirements of
       *    all socket address types that the system supports.
       * b) enough storage to hold any type of socket address that the
       *    system supports.
       */
    };
posted @ 2009-06-11 22:45  一只灰色的羊  阅读(340)  评论(0编辑  收藏  举报