Linux高性能服务器编程(第二篇 深入解析高性能服务器编程)
第5章 Linux网络编程基础API
1. socket地址API
- 主机字节序和网络字节序:32位机一次性装载4字节,字节排列顺序影响装载后整数的值。现代PC大多采用小端字节序,因此小端字节序也称主机字节序。发送端统一发送大端字节序,因此大端字节序也称网络字节序。
#include <iostream>
using namespace std;
#include <netinet/in.h>
unsigned long int htonl(unsigned long int hostlong);
unsigned short int htons(unsigned short int hostlong);
unsigned long int ntohl(unsigned long int netlong);
unsigned short int ntohs(unsigned short int netshort);
int main()
{
union {
short value;
char union_bytes[sizeof(short)];
} test;
test.value = 0x0102;
if ((test.union_bytes[0] == 1) && (test.union_bytes[1] == 2))
{
cout << "Big Endian" << endl;
}
else if ((test.union_bytes[0] == 2) && (test.union_bytes[1] == 1))
{
cout << "Little Endian" << endl;
}
else
{
cout << "Unknown..." << endl;
}
return 0;
}
2. 创建socket
#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
3. 命名socket
- 创建socket时指定了协议族,但未指定具体地址,将一个socket与socket地址绑定称为给socket命名;服务器需要命名socket,但客户端通常匿名,由操作系统自动分配socket地址。
#include <sys/types.h>
#include <sys/socket.h>
int bind(int sockfd,const struct sockaddr* my_addr,socklen_t addrlen);
4. 监听socket
- 服务器要创建监听队列存放待处理的客户连接
- 完整连接最多有 b a c k l o g + 1 backlog+1 backlog+1个
#include <sys/types.h>
#include <sys/socket.h>
int listen(int sockfd,int backlog);