套接字建立过程:
srever:
1 socket创建套接字
2 bind ip和port
3 listen
4 accept
5 read/write
6 close
client:
1 socket
2 connect
3 read/write
4 close
int socket(int domain, int type, int protocol);
//失败返回-1,成功返回文件描述符
//domain 套接字协议族 type数据类型 protocol通信协议信息
int bind(int sockfd, struct sockaddr *myaddr, socklen_t addrlen);
int listen(int sockfd, int backlog);
int accept(int sockfd, struct sockaddr *addr,socklen_t *addrlen);
int connect(int sockfd, struct,sockaddr *serv_addr, socklen_t, addrlen);
/*
成功返回0,失败返回-1
*/
协议族:
PF_INET, PF_INET6,PF_LOCAL等
套接字类型:
SOCK_STREAM 面向连接
SOCK_DGRAM 面向消息
文件描述符:
int open(const char *path, int flag);
//path 地址,flag打开方式
int close(int fd);
//成功返回0,失败返回-1
//写入文件:
ssize_t write(int fd, const void *buf, size_t, ntypes);
//失败返回-1,成功返回写入的字节数
//读取文件
ssize_t read(int fd, void *buf, size_t nbytes);
//失败返回-1,成功返回接收的字节数
IPv4结构体
struct sockaddr_in
{
sa_family_t sin_family; //地址族
uint16_t sin_port; //端口号
struct in_addr sin_addr; //32位ip
char sin_zero[8];//不使用
};
struct in_addr
{
In_addr_t s_addr; //32位iPv4地址
}
地址族: AF_INET,AF_INET6,AF_LOCAL
字节序转换:
unsigned short htons(unsigned short);
unsigned short ntohs(unsigned short);
unsigned short htonl(unsigned short);
unsigned short ntohl(unsigned short);
/*
h代表主机(host)字节序
n代表网络(network)字节序
s是short
l是long
*/
in_addr_t inet_addr(const char *string);
//返回32位大端整数值,失败返回INADDR_NONE
int inet_aton(const char *string, struct in_addr * addr);
//成功返回1,失败返回0
//将字符串32位ip地址转换为整数
char *inet_ntoa(struct in_addr adr);
//成功返回地址值,失败返回-1
//将整数ip转换为字符串
UDP函数
ssize_t sendto(int sock, void *buff, size_t ntypes, int flags, struct sockaddr *to, socklen_t addrlen);
ssize_t recvfrom(int sock, void *buff, size_t nbytes, int flags, struct sockaddr *from, socklen_t *addrlen);
断开函数shutdown
int shutdown(int sock, int howto);
/*
第二个参数是断开方式:
SHUT_RD 断开输入流
SHUT_WR 断开输出流
SHUT_RDWR 同时断开O/I流
*/
IP与域名的转换
struct hostent * gethostbyname(const char *hostname);
//通过域名获得ip
struct hostent * gethostbyaddr(const char *addr, socklen_t len, int family);
//通过ip获得域相关信息
struct hostent
{
char * h_name; //official name
char ** h_aliases; //alias list
int h_addrtype; //host address type
int h_length; //address length
char ** h_addr_list; //address list
};