gpt4 book ai didi

C TCP 客户端无法连接到服务器

转载 作者:行者123 更新时间:2023-11-30 18:15:21 25 4
gpt4 key购买 nike

我正在编写一个基本的 TCP 客户端,我正在尝试连接到我已经确保可以正常工作的 TCP 服务器。由于某种原因,我的客户端无法连接到服务器。它不会通过连接尝试。客户端和服务器都在同一台机器上,我使用 127.0.0.1 和端口 8080。有任何关于为什么的指示吗?谢谢!

/*
Usage: tcpclient <server_ip> <server_port> <client ip> <input_file> <output_file> <size of send/receive buffer>
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc, char ** argv) {
char* server_ip;
char* client_ip;
char* input_file;
char* output_file;
int server_port, buffer_size;

server_ip = argv[1];
server_port = atoi(argv[2]);
client_ip = argv[3];
input_file = argv[4];
output_file = argv[5];
buffer_size = atoi(argv[6]);

int sockfd = 0;
int bitsSent = 0;
int bitsReceived = 0;

char sendBuffer[buffer_size];
char recvBuffer[buffer_size];

struct sockaddr_in serv_addr;

memset(recvBuffer, '0', sizeof(recvBuffer));
memset(sendBuffer, '0', sizeof(sendBuffer));
memset((char *)&serv_addr,0,sizeof(serv_addr));


/* Check command line arguments */
if (argc != 7) {
exit(0);
}

/* Create the socket */
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(server_port);
serv_addr.sin_addr.s_addr = inet_addr(server_ip);

/* Attempt to connect to server */
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0) {
printf("Err: Couldn't connect");
return 1;
}

/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");

if (fp == NULL) {
perror("Error opening the file");
return(-1);
}

/* Receive the data then write to sendBuffer */
while ((bitsSent = read(sockfd, recvBuffer, buffer_size)) >0) {
printf("Bytes received: %d\n", bitsReceived);
fwrite(recvBuffer, 1, bitsReceived, fp);
}

if (bitsReceived < 0) {
printf("Read Error");
}

return 0;

}

最佳答案

您在创建套接字之前尝试连接。由于此时 sockfd 为零,因此您正在尝试连接标准输入。

关于C TCP 客户端无法连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677246/

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