我正在编写一个基本的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;
}
答案 0 :(得分:0)
在创建套接字之前,您正尝试connect
。由于此时sockfd
为零,因此您尝试connect
标准输入。
答案 1 :(得分:-2)
我不记得那是否相关,而不是:
serv_addr.sin_addr.s_addr = inet_addr(server_ip);
尝试:
inet_aton("127.0.0.1",&server_addr.sin_addr);
正如另一个回复说你忘了创建套接字:
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror("Error al crear el socket");
exit(1);
}