c语言tcp员工管理系统的登陆界面服务端的代码
时间: 2024-05-10 22:18:19 浏览: 85
下面是一个简单的C语言TCP员工管理系统的登陆界面服务端的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 8080
#define MAX_CLIENTS 30
typedef struct {
char username[20];
char password[20];
} User;
User users[] = {{"user1", "password1"}, {"user2", "password2"}, {"user3", "password3"}};
int validate_user(char *username, char *password) {
for (int i = 0; i < sizeof(users) / sizeof(User); i++) {
if (strcmp(users[i].username, username) == 0 && strcmp(users[i].password, password) == 0) {
return 1;
}
}
return 0;
}
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *message = "Welcome to the employee management system!\nPlease enter your username and password, separated by a space.\n";
int max_clients = MAX_CLIENTS;
int client_sockets[MAX_CLIENTS] = {0};
// Create server socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Set socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
// Set server address
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind socket to address
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// Accept incoming connections
while (1) {
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Send welcome message to client
send(new_socket, message, strlen(message), 0);
// Receive username and password from client
read(new_socket, buffer, 1024);
// Validate username and password
char *username = strtok(buffer, " ");
char *password = strtok(NULL, " ");
if (validate_user(username, password)) {
send(new_socket, "Login successful!\n", strlen("Login successful!\n"), 0);
} else {
send(new_socket, "Invalid username or password.\n", strlen("Invalid username or password.\n"), 0);
}
// Add client socket to array
for (int i = 0; i < max_clients; i++) {
if (client_sockets[i] == 0) {
client_sockets[i] = new_socket;
break;
}
}
}
return 0;
}
```
这个代码演示了如何创建一个简单的TCP服务器,以便用户可以通过套接字连接到它,并在终端中输入用户名和密码来进行身份验证。在这个例子中,我们使用了一个硬编码的用户列表,但是在实际应用中,你需要从数据库或其他存储中读取用户信息。
阅读全文