c - memcpy: unix socket sun_path 起始地址索引

标签 c sockets memcpy

所以我有如下用于 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 expr 的 + 1 部分。

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

最佳答案

根据 man-page ,通过sockaddr_un结构可以区分三种类型的地址:pathname、unnamed和abstract。

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

*  abstract: an abstract socket address is distinguished (from a
   pathname socket) by the fact that sun_path[0] is a null byte
   ('\0').  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.

关于c - memcpy: unix socket sun_path 起始地址索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30458429/

相关文章:

c - 如何像在 PHP 中一样使用 c 处理 CGI 中的 session

命令行参数未正确传递

c++ - 是什么导致 fprintf 出现 C++ 缓冲区溢出错误?

c - C 套接字中的非阻塞 recv()

c - ANSI C memcpy/w 函数调用。 2个例子。 1 个有效,1 个无效。

c++ - POD 类型的二进制 I/O 如何不破坏别名规则?

c++ - 关闭管道时收到双重释放或损坏(顶部)?

c - 为什么我的程序只能在调试器中运行?

c - Linux C 客户端接收 0 字节,而服务器未发送任何内容

C - memcpy 和复制结构