memcpy: unix 套接字 sun_path 的起始地址索引

memcpy: starting address index of sun_path of unix socket

所以我有如下用于 unix 套接字初始化的代码

#define IETADM_NAMESPACE "IET_ABSTRACT_NAMESPACE"

struct sockaddr_un addr;

memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_LOCAL;

memcpy((char *) &addr.sun_path + 1, IETADM_NAMESPACE, strlen(IETADM_NAMESPACE));

我得到 memcpy 副本 IETADM_NAMESPACE 从索引地址开始,即 &addr.sun_path + 1.

我的问题是关于 &addr.sun_path + 1 表达式的 + 1 部分。

为什么地址增加并复制到那里而不是仅仅复制字符串 &addr.sun_path?

man 7 unix 有答案:

Address format

[...]

abstract: an abstract socket address is distinguished (from a
          pathname socket) by the fact that sun_path[0] is a null byte
          ('[=10=]').  The socket's address in this namespace is given by the
          additional bytes in sun_path that are covered by the specified
          length of the address structure.  (Null bytes in the name have no
          special significance.)  The name has no connection with filesystem
          pathnames.  When the address of an abstract socket is returned,
          the returned addrlen is greater than sizeof(sa_family_t) (i.e.,
          greater than 2), and the name of the socket is contained in the
          first (addrlen - sizeof(sa_family_t)) bytes of sun_path.  The
          abstract socket namespace is a nonportable Linux extension.

根据man-pagesockaddr_un结构可以区分三种地址:pathname、unnamed和abstract。

您提供的代码显示在 memcpy 之后,sun_path 成员的第一个字节将是 '[=14=]',因为之前的 memset。引用手册页的相关部分:

*  abstract: an abstract socket address is distinguished (from a
   pathname socket) by the fact that sun_path[0] is a null byte
   ('[=10=]').  The socket's address in this namespace is given by the
   additional bytes in sun_path that are covered by the specified
   length of the address structure.  (Null bytes in the name have no
   special significance.)  The name has no connection with filesystem
   pathnames.  When the address of an abstract socket is returned,
   the returned addrlen is greater than sizeof(sa_family_t) (i.e.,
   greater than 2), and the name of the socket is contained in the
   first (addrlen - sizeof(sa_family_t)) bytes of sun_path.  The
   abstract socket namespace is a nonportable Linux extension.