gpt4 book ai didi

c - 在 C 中使用套接字

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:56 25 4
gpt4 key购买 nike

我正在尝试为聊天室创建一个基本的客户端服务器套接字程序。目前它将第一条消息作为登录名发送到服务器并打印出正确的内容,但客户端在那之后崩溃并且不允许我向服务器发送另一条消息。下面是代码

客户端代码

#include <stdio.h>
#include "winsock2.h"

#define SERVER_PORT 9999
#define MAX_LINE 256
void main(int argc, char **argv) {

if (argc < 2){
printf("\nUseage: client serverName\n");
return;
}

// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR ){
printf("Error at WSAStartup()\n");
return;
}

//translate the server name or IP address (128.90.54.1) to resolved IP address
unsigned int ipaddr;
// If the user input is an alpha name for the host, use gethostbyname()
// If not, get host by addr (assume IPv4)
if (isalpha(argv[1][0])) { // host address is a name
hostent* remoteHost = gethostbyname(argv[1]);
if ( remoteHost == NULL){
printf("Host not found\n");
WSACleanup();
return;
}
ipaddr = *((unsigned long *) remoteHost->h_addr);
}
else //"128.90.54.1"
ipaddr = inet_addr(argv[1]);


// Create a socket.
SOCKET s;

// Connect to a server.
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = ipaddr;
addr.sin_port = htons( SERVER_PORT );
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return;
}
if (connect(s, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) {
printf("Failed to connect.\n");
WSACleanup();
return;
}

while (1) {

// Send and receive data.
char buf[MAX_LINE];
printf("Type whatever you want: ");
scanf("%[^\n]", buf);
send(s, buf, strlen(buf), 0);
char recieve[MAX_LINE];
int len = recv(s, recieve, MAX_LINE, 0);
recieve[len] = 0;
printf("Server says: %s\n", recieve);
closesocket(s);
}



}

服务器代码

#include <stdio.h>
#include "winsock2.h"

#define SERVER_PORT 9999
#define MAX_PENDING 5
#define MAX_LINE 256
#define MAX_USERS 10

char users[MAX_USERS][MAX_LINE];
char passwords[MAX_USERS][MAX_LINE];
int count = 0;
int loggedin = 0;
char* Login(char*, char*);
char* username = NULL;
void main() {

// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
printf("Error at WSAStartup()\n");
return;
}

// Create a socket.
SOCKET listenSocket;
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (listenSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return;
}

// Bind the socket.
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY; //use local address
addr.sin_port = htons(SERVER_PORT);
if (bind(listenSocket, (SOCKADDR*)&addr, sizeof(addr)) == SOCKET_ERROR) {
printf("bind() failed.\n");
closesocket(listenSocket);
WSACleanup();
return;
}

// Listen on the Socket.
if (listen(listenSocket, MAX_PENDING) == SOCKET_ERROR) {
printf("Error listening on socket.\n");
closesocket(listenSocket);
WSACleanup();
return;
}

// Accept connections.
SOCKET s;
FILE* file = fopen("C:\\Users\\Brandon\\Desktop\\server2\\users.txt", "r");
if (file == NULL) {
printf("file didnt open");
exit(1);
}
char* user = (char*)malloc(MAX_LINE);
char* password = (char*)malloc(MAX_LINE);
int i = 0;
while (fscanf(file, "%s %s", user, password) != EOF) {
strcpy(users[i], user);
strcpy(passwords[i], password);
i++;
}
count = i;
printf("Waiting for a client to connect...\n");
while (s = accept(listenSocket, NULL, NULL)) {
if (s == SOCKET_ERROR) {
printf("accept() error \n");
closesocket(listenSocket);
WSACleanup();
return;
}
// Send and receive data.
char buf[MAX_LINE];
char buf1[MAX_LINE];
int len = recv(s, buf, MAX_LINE, 0);
buf[len] = 0;
char* type = strtok(buf, " ");
char* username = strtok(NULL, " ");
char* password1 = strtok(NULL, " ");
if (strcmp(type, "login") == 0) {
strcpy(buf1, Login(username, password1));
}
send(s, buf1, strlen(buf1), 0);
closesocket(s);
printf("Client Closed.\n");
}

closesocket(listenSocket);
}

char* Login(char* username1, char* password) {
for (int i = 0; i < count; i++) {
if (strcmp(users[i], username1) == 0 && strcmp(passwords[i], password) == 0) {
printf("%s logged in.\n", username1);
loggedin = 1;
username = username1;
return strcat(username1, " Has logged in\n");
}
}
return "User name and password are incorrect";
}

char* Logout() {
printf("%s logout.", username);
loggedin = 0;
return strcat(username, " left");
}

最佳答案

这个:'buf[len] = 0;'如果 recv() 调用加载了 MAX_LINE 个字符,则写入越界。使用 MAX_LINE-1 调用 recv() 以防止出现这种情况。客户端和服务端都有这个问题。

用 strtok 等解析 'buf' 是不安全的。不能保证通过一次调用 recv() 加载完整的应用程序级消息。 TCP 不能传输大于一个字节的消息。如果你想传输字符串,你需要一个顶层协议(protocol),例如,重复调用直到收到一些消息结束字符(例如换行符或 NUL)。

关于c - 在 C 中使用套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37013150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com