I'm writing a basic TCP Client that I'm trying to connect to a TCP Server that I have already made sure works. For some reason, my client won't connect to the server. It will not get past the connection attempt. Both client and server are on the same machine, I'm using 127.0.0.1 for both and port 8080. Any pointers as to why? Thanks!
/*
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;
}
printf()and useperror().No hope of a solution until we know what the problem is. When you get an error, print the error. You already know it failed: just printing that information is useless. Same applies after the read/write loop. - user207421bitsSend/bitsReceivedsuch namings are defintily missleading. - alk