Linux recvmsg函數(shù)的實(shí)際應(yīng)用案例

小樊
95
2024-08-26 14:21:53

recvmsg函數(shù)是Linux系統(tǒng)中用于接收套接字?jǐn)?shù)據(jù)的函數(shù),在網(wǎng)絡(luò)編程中經(jīng)常會(huì)用到。下面是一個(gè)簡(jiǎn)單的實(shí)際應(yīng)用案例:

假設(shè)有一個(gè)服務(wù)器程序,監(jiān)聽(tīng)某個(gè)端口,客戶(hù)端連接后會(huì)發(fā)送數(shù)據(jù)給服務(wù)器。服務(wù)器程序需要接收客戶(hù)端發(fā)送的數(shù)據(jù),并進(jìn)行處理。

以下是一個(gè)簡(jiǎn)單的使用recvmsg函數(shù)接收客戶(hù)端數(shù)據(jù)的示例代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8888
#define BUF_SIZE 1024

int main() {
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t addr_len = sizeof(client_addr);
    char buffer[BUF_SIZE];

    // 創(chuàng)建套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    // 綁定地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    // 監(jiān)聽(tīng)端口
    if (listen(server_fd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    // 接受連接
    client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
    if (client_fd == -1) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    // 接收數(shù)據(jù)
    ssize_t num_bytes = recv(client_fd, buffer, BUF_SIZE, 0);
    if (num_bytes == -1) {
        perror("recv");
        exit(EXIT_FAILURE);
    }

    // 打印接收到的數(shù)據(jù)
    printf("Received data: %s\n", buffer);

    // 關(guān)閉套接字
    close(client_fd);
    close(server_fd);

    return 0;
}

上面的代碼示例中,服務(wù)器程序通過(guò)recv函數(shù)接收客戶(hù)端發(fā)送的數(shù)據(jù),并打印出來(lái)。在實(shí)際應(yīng)用中,可以根據(jù)接收到的數(shù)據(jù)進(jìn)行相應(yīng)的處理,比如解析數(shù)據(jù)內(nèi)容、回復(fù)客戶(hù)端等操作。

0