在C语言中,可以使用socket库来处理网络信息。以下是一个简单的例子,演示如何使用C语言接收和发送数据:
#include
#include
#include
#include
#include
#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”的消息给客户端。