主机字节和网络字节转换API:
#include <netinet/in.h>
//主机字节转换成网络字节
unsigned short inthtons(unsigned short inthostshrot);
//网络字节转换成主机字节
unsigned short intntohs(unsigned short intnetshrot);
专用socket地址结构体:
//TCP/IP协议族专用socket地址结构体
structsockaddr_in
{
sa_family_t sin_family; //地址族:AF_INET
u_int16_t sin_port; //端口号, 要用网络字节序表示
struct in_addr sin_addr; //IPv4地址结构体,是u_int32_t s_addr;
};
IP转换函数:
#include <arpa/inet.h>
//将字符串IP转换为整数IP
intinet_pton(intaf, const char* src,void* dst);
//将整数IP转换成字符串IP
const char* inet_ntop(intaf, const void* dst,socklen_tcnt);
创建socket:
#include <sys/types>
#incliude <sys/socket.h>
/*
domain:底层协议族类型
type: 指定服务类型
protocol :具体的协议
*/
int socket(int domain, int type, int protocol);
命令socket:
#include <sys/types>
#include <sys/socket.h>
// 服务器绑定网络地址
int bind(intsockfd, const structsockeaddr* addr,socketlen_taddrlen);
bind函数成功返回0,否则为-1,常见errno类型:
监听socket:
#include <sys/socket.h>
int listen(intsockfd,int backlog);
接收连接API:
#include <sys/types.h>
#include <sys/socket.h>
int accept(intsockfd,structsockaddr* addr,socklen_t* addrlen);
发起连接API:
#include <sys/types.h>
#include <sys/socket.h>
int connect(intsockfd,conststructsockaddr* serv_addr,socklen_taddrlen);
connect函数成功返回0,否则为-1,常见errno类型:
关闭连接API:
#include <unistd.h>
#include <sys/socket.h>
int close(intfd);
int shutdown(intsockfd,inthowto);
shutdown函数中howto参数选项
TCP数据读写API:
#include <sys/types.h>
#include <sys/socket.h>
ssize_trecv(intsockfd,void* buf,size_tlen,int flags);
ssize_t send(intsockfd,cons void* buf,size_tlen,int flags);
recv函数和send函数的flags参数选项
UDP数据读写API:
#include <sys/types.h>
#include <sys/socket.h>
ssize_trecvfrom(intsockfd,void* buf,size_tlen,intflags,structsockaddr* src_addr,socklen_t* addrlen);
ssize_tsendto(intsockfd,cons void* buf,size_tlen,intflags,conststructsockaddr* dest_addr,sockelen_taddrlen);