Socket套接字函数是用于网络编程的一组API,用于在网络上进行通信。这些函数提供了一种通用的接口,使得程序能够通过网络连接进行数据的发送和接收。下面是对常见的几个Socket函数及其参数的解释:
socket()函数:
bind()函数:
listen()函数:
accept()函数:
connect()函数:
这些Socket函数与内核函数之间的关系可以用下图表示:
- +---------------------+ +---------------------+
- | Application | | Kernel |
- +---------------------+ +---------------------+
- | |
- | Socket API |
- | (e.g., socket(), |
- | bind(), listen()) |
- |------------------------->| |
- | System Calls |
- |------------------------->| |
- | |
- | Network Stack |
- |------------------------->| |
- | |
- | Network Hardware |
- |<------------------------| |
- | |
服务端的代码 :
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main() {
- int server_fd, new_socket;
- struct sockaddr_in address;
- int opt = 1;
- int addrlen = sizeof(address);
- char buffer[1024] = {0};
- char *hello = "Hello from server";
-
- // 创建socket文件描述符
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
- perror("socket failed");
- exit(EXIT_FAILURE);
- }
-
- // 绑定socket到8080端口
- address.sin_family = AF_INET;
- address.sin_addr.s_addr = INADDR_ANY;
- address.sin_port = htons(8080);
-
- if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
- perror("bind failed");
- exit(EXIT_FAILURE);
- }
-
- // 监听此端口,等待客户端连接
- if (listen(server_fd, 3) < 0) {
- perror("listen");
- exit(EXIT_FAILURE);
- }
-
- // 接受客户端连接
- if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
- perror("accept");
- exit(EXIT_FAILURE);
- }
-
- // 读取客户端发送的数据
- read( new_socket , buffer, 1024);
- printf("%s\n",buffer );
-
- // 向客户端发送数据
- send(new_socket , hello , strlen(hello) , 0 );
- printf("Hello message sent\n");
-
- // 关闭socket
- close(server_fd);
- return 0;
- }
客户端的代码:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
-
- int main() {
- struct sockaddr_in serv_addr;
- int sock = 0;
- char *hello = "Hello from client";
- char buffer[1024] = {0};
-
- // 创建socket
- if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
- printf("\n Socket creation error \n");
- return -1;
- }
-
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(8080);
-
- // 将IPv4地址从文本转换为二进制形式
- if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
- printf("\nInvalid address/ Address not supported \n");
- return -1;
- }
-
- // 连接到服务器
- if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
- printf("\nConnection Failed \n");
- return -1;
- }
-
- // 向服务器发送数据
- send(sock , hello , strlen(hello) , 0 );
- printf("Hello message sent\n");
-
- // 读取服务器回传的数据
- read( sock , buffer, 1024);
- printf("%s\n",buffer );
-
- // 关闭socket
- close(sock);
- return 0;
- }