用Linux系统c语言编写一个基于TCP协议的网络通信程序,要求服务器通过套接字连接后,要求输入用户名,判断用户名正确后,向客户端发送连接正确的字符串,在服务器显示客户端的IP地址和端口
时间: 2024-02-29 19:52:30 浏览: 72
好的,下面是一个简单的示例,仅供参考:
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define MAXLINE 1024
int main(int argc, char *argv[])
{
int listenfd, connfd;
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddr_len;
char buf[MAXLINE];
char username[] = "admin"; // 此处设置默认用户名为"admin"
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("bind");
exit(1);
}
if (listen(listenfd, 10) == -1) {
perror("listen");
exit(1);
}
printf("Server is listening on port %d...\n", PORT);
while (1) {
cliaddr_len = sizeof(cliaddr);
if ((connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &cliaddr_len)) == -1) {
perror("accept");
continue;
}
printf("Client %s:%d connected.\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
// 接收客户端发送的用户名
memset(buf, 0, MAXLINE);
if (recv(connfd, buf, MAXLINE, 0) == -1) {
perror("recv");
close(connfd);
continue;
}
// 判断用户名是否正确
if (strcmp(buf, username) == 0) {
// 发送连接正确的字符串
char *msg = "Connection established.\n";
if (send(connfd, msg, strlen(msg), 0) == -1) {
perror("send");
}
} else {
// 发送连接错误的字符串
char *msg = "Connection refused.\n";
if (send(connfd, msg, strlen(msg), 0) == -1) {
perror("send");
}
close(connfd);
continue;
}
close(connfd);
}
close(listenfd);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8888
#define MAXLINE 1024
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
char buf[MAXLINE];
char username[MAXLINE];
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(SERVER_IP);
servaddr.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("connect");
exit(1);
}
printf("Please enter your username: ");
fgets(username, MAXLINE, stdin);
// 发送用户名给服务器
if (send(sockfd, username, strlen(username), 0) == -1) {
perror("send");
exit(1);
}
// 接收服务器返回的消息
memset(buf, 0, MAXLINE);
if (recv(sockfd, buf, MAXLINE, 0) == -1) {
perror("recv");
exit(1);
}
printf("%s", buf);
close(sockfd);
return 0;
}
```
编译命令:
```
gcc server.c -o server
gcc client.c -o client
```
运行命令:
```
./server
./client
```
阅读全文