如何用C語(yǔ)言處理網(wǎng)絡(luò)info

小樊
84
2024-08-26 14:20:34

在C語(yǔ)言中,可以使用socket庫(kù)來(lái)處理網(wǎng)絡(luò)信息。以下是一個(gè)簡(jiǎn)單的例子,演示如何使用C語(yǔ)言接收和發(fā)送數(shù)據(jù):

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

#define PORT 8080

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    char *hello = "Hello from server";

    // 創(chuàng)建socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 綁定端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 監(jiān)聽(tīng)端口
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }

    // 接受連接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        perror("accept failed");
        exit(EXIT_FAILURE);
    }

    // 讀取數(shù)據(jù)
    read(new_socket, buffer, 1024);
    printf("Received: %s\n", buffer);

    // 發(fā)送數(shù)據(jù)
    send(new_socket, hello, strlen(hello), 0);
    printf("Hello message sent\n");

    return 0;
}

在這個(gè)例子中,我們創(chuàng)建了一個(gè)服務(wù)器,綁定到8080端口,并監(jiān)聽(tīng)來(lái)自客戶(hù)端的連接。當(dāng)客戶(hù)端連接成功后,服務(wù)器接收客戶(hù)端發(fā)送的數(shù)據(jù)并打印出來(lái),然后發(fā)送一個(gè)”Hello from server”的消息給客戶(hù)端。

0