Linux程序设计.编写一个以客户机/服务器模式工作的程序,要求在客户端读取系统文件/etc/passwd内容,传送到服务端,服务器端接收字符串,并在显示器显示出来。
时间: 2024-02-20 14:01:49 浏览: 60
好的,这是一个基于Socket的客户端/服务器端程序,可以实现你的需求。以下是基本的代码框架,你可以根据需要进行修改和完善:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int server_socket;
int client_socket;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
char message[BUF_SIZE];
int str_len, i;
if(argc != 2) {
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
server_socket = socket(PF_INET, SOCK_STREAM, 0);
if(server_socket == -1) {
perror("socket() error");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[1]));
if(bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind() error");
exit(1);
}
if(listen(server_socket, 5) == -1) {
perror("listen() error");
exit(1);
}
while(1) {
socklen_t client_addr_size = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_size);
if(client_socket == -1) {
perror("accept() error");
exit(1);
}
str_len = read(client_socket, message, BUF_SIZE);
if(str_len == -1) {
perror("read() error");
exit(1);
}
printf("Received message from client: %s", message);
write(client_socket, message, str_len);
close(client_socket);
}
close(server_socket);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
int client_socket;
struct sockaddr_in server_addr;
char message[BUF_SIZE];
int str_len;
if(argc != 3) {
printf("Usage: %s <IP> <port>\n", argv[0]);
exit(1);
}
client_socket = socket(PF_INET, SOCK_STREAM, 0);
if(client_socket == -1) {
perror("socket() error");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));
if(connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("connect() error");
exit(1);
}
FILE *fp = fopen("/etc/passwd", "r");
if(fp == NULL) {
perror("fopen() error");
exit(1);
}
while(fgets(message, BUF_SIZE, fp)) {
write(client_socket, message, strlen(message));
str_len = read(client_socket, message, BUF_SIZE-1);
if(str_len == -1) {
perror("read() error");
exit(1);
}
message[str_len] = 0;
printf("Received message from server: %s", message);
}
fclose(fp);
close(client_socket);
return 0;
}
```
注意:此代码仅作为参考,具体实现可能会有所不同,需要根据实际情况进行修改。同时,为了保证安全性,建议在传输敏感数据时加密传输。
阅读全文