TCP/IP编程 - 1) 基础知识

1. What Is a Socket?(什么是套接字)

 

A socket is an abstraction through which an application may send and receive data, in much
the same way as an open-file handle allows an application to read and write data to stable
storage.

 

简单来说,套接字就是网络数据传输用的软件设备。

 

举个生活中的例子:

我们把插头插到插座上就能从电网获得电力供应,同样道理,为了与远程计算机

进行数据通信,需要连接到Internet,而套接字就是用来连接网络的工具。

 

A socket allows an application to plug in to the network and communicate with other
applications that are plugged in to the same network. Information written to the socket by
an application on one machine can be read by an application on a different machine and vice
versa.

 

TCPIP套接字网络原理图:

 

2. 套接字网络编程的步骤

 

a. 服务端

step1: 调用socket函数创建套接字

step2: 调用bind函数分配IP地址和端口号

step3: 调用listen函数转为可接收请求状态

step4: 调用accept函数受理连接请求

 

b. 客户端

step1: 调用socket函数创建套接字

step2: 调用connect函数向服务端发送连接请求

 

3. 各函数介绍

 

1) socket()函数

#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);


这个函数建立一个协议族为domain,协议类型为type,协议编号为protocol的

套接字文件描述符。

domain: 协议族, 通常为AF_NET(TCPIP协议族), 以太网使用PF_INET

type: 通信类型

    SOCK_STREAM(流式套接字)

    SOCK_DGRAM(数据包套接字)

protocol: 协议的特定类型,通常为0

 

2) bind()函数

#include <sys/types.h>
#include <sys/socket.h>
int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);

这个函数将长度为addrlen的sockaddr结构类型参数my_addr和sockfd绑定在一起

 

3. listen()函数

这个函数用来监听端口

#include <sys/socket.h>
int listen(int sockfd, int backlog);


 

4. accept()函数

#include <sys/types.h>
#include <sys/socket.h>
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

通过accept()函数可以得到成功连接客户端的IP地址,端口和协议族等信息,这个信息是通过

参数addr获得的。

 

5. connect()函数 - 客户端

#include <sys/types.h>
#include <sys/socket.h>
int connect(int sockfd, struct sockaddr *serv_addr, int addrlen);

这个函数用来连接网络目标服务器。
其中,参数ser_addr结构包含了需要连接的目的服务器的端口和IP地址,以及协议类型。

 

转载于:https://www.cnblogs.com/davidgu/p/4823290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值