Skip to content
On this page

connect(2)


标签:linux/network  

函数原型

功能:连接到指定的服务器上

c
#include <sys/types.h>          /* See NOTES */ 
#include <sys/socket.h> 
 
int connect(int sockfd, const struct sockaddr *addr,
             socklen_t addrlen);

参数

  • int sockfd:指定要将哪个客户端套接字与服务器连接;
  • struct sockaddr *addr:通用地址信息结构体,真实的地址信息结构体根据地址族指定。填上需要连接的服务器的IP和端口; (参考bind(2)

返回值

成功,返回 0; 失败,返回 -1,更新 errno。

🔖UDP 的 connect 函数

UDP 中是可以使用 connect 函数。[^1]

使用效果:

  1. TCP 中的 connect 函数会产生三次握手,会将 client 和 server 连接
  2. UDP 中的 connect 函数不会产生连接,仅仅是将对端的 IP 和端口号记录到内核的套接字文件中,此时 UDP 只能与记录的对端进行通信

多次使用:

  1. TCP 中只能 connect 一次
  2. UDP 中的 connect 函数可以被多次调用,刷新内核中对端的 IP 地址和端口
  3. 如果想要清空内核中对端的地址信息,则将sockaddr中的sa_family设置成AF_UNSPEC即可
  4. 当 UDP 采用 connect 方式收发报文后,可以调用
c
recvfrom(sockfd, buf, len, flags, NULL, NULL);
sendto(sockfd, buf, len, flags, NULL, 0);

UDP 中使用 connect 有什么优点?

  1. 提升传输效率
    • 不调用 connect 的 UDP 通信:将对端的信息填充到内核中 --> 发送报文 --> 清空内核中的信息 --> 将对端的信息填充到内核中 --> 发送报文 --> 清空内核信息
    • 调用 connect 的 UDP 通信:将对端的信息填充到内核中 --> 发送报文 --> 发送报文 --> 发送报文 --> 清空内核信息
  2. 增加传输稳定性
    • 调用 connect 的 UDP 通信可以防止 AB 进程在传输过程中接收到 C 的信息,造成错误

Question

  1. TCP 中能否使用 read recvfrom;TCP 中能否使用 write sendto
  2. UDP 中能否使用 read recv;UDP 中能否使用 write, send(UDP 中的 connect 函数)
  3. UDP 中能否使用 connect 函数(可以+ TCP 和 UDP 中的 connect 的区别)

相关笔记

[^1]: connect(2) - Linux manual page (man7.org)

Last updated: