用C语言按要求写出接收端与发送端代码
时间: 2024-11-09 13:23:21 浏览: 3
在C语言中,编写简单的TCP/IP网络通信程序通常涉及使用套接字(sockets)。这里我会给你展示一个基本的客户端和服务器端的例子,使用的是Berkeley Socket API。注意,这只是一个基础示例,并未涵盖完整的错误检查和异常处理,实际应用中需要更详细的代码:
### 发送端 (client.c) 示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int client_sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
char message[] = "Hello Server!";
// 设置服务器地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080); // 端口号假设是8080
inet_aton("localhost", &server_addr.sin_addr);
// 连接到服务器
if (connect(client_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("Failed to connect");
return 1;
}
// 发送数据
write(client_sock, message, strlen(message));
// 关闭连接并退出
close(client_sock);
printf("Message sent successfully.\n");
return 0;
}
```
### 接收端 (server.c) 示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int main() {
int server_sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
socklen_t addr_len = sizeof(server_addr);
// 绑定本地地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY; // 任意地址
server_addr.sin_port = htons(8080);
bind(server_sock, (struct sockaddr *)&server_addr, addr_len);
// 开始监听
listen(server_sock, 5);
while (1) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_len);
// 接收数据
char buffer[1024];
ssize_t bytes_received = read(client_sock, buffer, sizeof(buffer));
buffer[bytes_received] = '\0'; // 添加终止符
// 打印接收到的信息
printf("Received: %s\n", buffer);
// 关闭客户端连接
close(client_sock);
}
return 0;
}
```
要编译这两个文件,你需要链接socket库 (-lsocket) 和 netdb库 (-lnetdb),例如:
```bash
gcc -o client client.c -lsocket -lnetdb
gcc -o server server.c -lsocket -lnetdb
```
然后分别运行`./client`和`./server`。
阅读全文