c语言编写程序实现一个简易的身份识别协议
时间: 2024-10-24 14:18:36 浏览: 15
RFID.rar_RFID C语言_RFID C语言编程_刷卡
在C语言中实现一个简单的身份识别协议通常涉及创建客户端和服务器之间的通信机制。一种常见的方案是使用TCP/IP网络编程,利用套接字来进行数据交换。这里我们可以创建一个基于用户名和密码验证的基本示例:
首先,我们创建一个服务器端程序,它监听连接并处理请求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 12345
void handle_client(int client_socket) {
char username[50], password[50];
int len;
if (recv(client_socket, username, sizeof(username), 0) == -1) {
perror("Reading from client");
close(client_socket);
}
memset(password, 0, sizeof(password)); // Clear buffer for security
printf("Received username: %s\n", username);
// Assume a hardcoded "admin" and "password123"
if (strcmp(username, "admin") == 0 && strcmp(password, "password123") == 0) {
printf("Authentication successful!\n");
send(client_socket, "Authenticated", strlen("Authenticated"), 0);
} else {
printf("Invalid credentials.\n");
send(client_socket, "Unauthorized", strlen("Unauthorized"), 0);
}
close(client_socket);
}
int main() {
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
listen(server_socket, 5);
while (1) {
int client_socket = accept(server_socket, NULL, NULL);
if (client_socket == -1) {
perror("Accepting connection");
continue;
}
handle_client(client_socket);
}
return 0;
}
```
然后,创建一个客户端,它尝试连接到服务器并发送用户名和密码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_IP "localhost"
#define SERVER_PORT 12345
int main() {
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);
if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Connecting to server");
exit(1);
}
char username[] = "admin";
char password[] = "password123";
send(client_socket, username, strlen(username), 0);
send(client_socket, password, strlen(password), 0);
char response[50];
recv(client_socket, response, sizeof(response), 0);
printf("Server response: %s\n", response);
close(client_socket);
return 0;
}
```
这个例子非常基础,实际应用中你需要考虑更安全的存储和传输策略,例如加密密码、使用哈希函数等。此外,你也可以添加错误处理和更复杂的用户认证逻辑。
阅读全文