#include <sys/types.h>         
#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
 
描述:
The  connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr.  The addrlen argument specifies the size of addr.  The format of the address in  addr  is  determined  by  the address space of the socket sockfd; see socket(2) for further details.

If  the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.  If the socket is of type SOCK_STREAM or SOCK_SEQPACKET,  this  call attempts to make a connection to the socket that is bound to the address specified by addr.

Generally,  connection-based  protocol sockets may successfully connect() only once; connectionless protocol sockets may use connect() multiple times to change their association.  Connectionless sockets may dissolve  the  association by  connecting to an address with the sa_family member of sockaddr set to AF_UNSPEC (supported on Linux since kernel 2.2).

 
返回值:
If the connection or binding succeeds, zero is returned.  On error, -1 is returned, and errno is set appropriately.
 
connect函数的功能是完成一个有连接协议的连接过程,对于TCP来说就是那个三次握手过程。
为了理解connect函数,我们需要对connect函数的功能进行介绍。connect函数的功能可以用一句话来概括,就是完成面向连接的协议的连接过程,它是主动连接的,面向连接的协议,在建立连接的时候总会有一方先发送数据,那么谁调用了connect谁就是先发送数据的一方。如此理解connect三个参数是容易了,我必需指定数据发送的地址,同时也必需指定数据从哪里发送,这正好是connect的前两个参数,而第三个参数是为第二个参数服务的。
 
 
sockfd,指定数据发送的套接字,解决从哪里发送的问题。内核需要维护大量IO通道,所以用户必需通过这个参数告诉内核从哪个IO通道,此处就是从哪个socket接口中发送数据。sockfd是先前socket()返回的值。
 
addr,指定数据发送的目的地,也就是服务器端的地址。这里服务器是针对connect说的,因为connect是主动连接的一方调用的,所以相应的要存在一个被连接的一方,被动连接的一方需要调用listen以接受connect的连接请求,如此被动连接的一方就是服务器了。
 
addrlen,指定addr结构体的长度。我们知道系统中存在大量的地址结构,但socket接口只是通过一个统一的结构来指定参数类型,所以需要指定一个长度,以使内核在进行参数复制的时候有个有个界限。

最新文章

  1. asp.net获取服务器绝对路径和相对路径
  2. React Native 组件样式测试
  3. sql 中 in与exists的对比
  4. [蓝牙] 4、Heart Rate Service module
  5. 配置DB2的数据库ODBC连接
  6. linux复制多个文件到文件夹
  7. [一]初识Json
  8. UVA 712-S-Trees(满二叉树的简单查询)
  9. HTTP 响应
  10. 回调函数 use
  11. WebGL多模型光照综合实例
  12. Photoshop给人像加上个性裂纹肌肤
  13. C#.NET开源项目、机器学习、Power BI
  14. JavaScript中,JSON格式的字符串与JSON格式的对象相互转化
  15. 10 Tips for Writing Better Code (阅读理解)
  16. 《剑指offer》 大数递增
  17. 内置函数id,返回内存地址
  18. 使用RxSwift 实现登录页面的条件绑定
  19. MySQL查询表结构命令
  20. maven(2)------maven构建项目

热门文章

  1. 【二分答案】bzoj1639 [Usaco2007 Mar]Monthly Expense 月度开支
  2. 【可持久化Trie】模板
  3. 1.3(Spring学习笔记)Spring-AOP
  4. pythonGUI编程打开默认浏览器
  5. md5代码实现
  6. iOS:CocosPods的装配和配置ReactiveCocoa
  7. 用ghost备份和还原Linux系统
  8. linux基础-第二十单元_计划任务crond服务
  9. makefile opencv的案例
  10. http://blog.chinaunix.net/uid-20577907-id-3519578.html