socket函数解析
概念:
每个进程的进程空间里都有一个socket描述符表。套接字描述符表属于一个进程,而socket地址结构位于操作系统的内核缓冲。
函数原型
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
函数参数
family参数
默认选择AF_INET
名称
目的
AF_INET
IPv4网络通信
AF_INET6
IPv6网络通信
AF_PACKET
链路层通信
AF_UNIX, AF_LOCAL
本地通信
type参数
protocol参数
- 可设置为0,表示选择当前family和type组合下protocol的系统默认值
IPPROTO_TCP
IPPTOTO_UDP
IPPROTO_SCTP
IPPROTO_TIPCTCP
TCP传输协议
UDP传输协议
STCP传输协议
TIPC传输协议
用法
如果我们在新建套接字的时候使用socket(PF_INET,SOCK_STREAM,0),那么内核就会默认给你把protocol修正为IPPROTO_TCP。
int lst_fd = -1;
lst_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (lst_fd < 0) {
perror("socket error");
return -1;
}