在C語言中,可以使用socket庫來處理網絡信息。以下是一個簡單的例子,演示如何使用C語言接收和發送數據:
#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";
// 創建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);
}
// 監聽端口
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);
}
// 讀取數據
read(new_socket, buffer, 1024);
printf("Received: %s\n", buffer);
// 發送數據
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
return 0;
}
在這個例子中,我們創建了一個服務器,綁定到8080端口,并監聽來自客戶端的連接。當客戶端連接成功后,服務器接收客戶端發送的數據并打印出來,然后發送一個”Hello from server”的消息給客戶端。