I'm writing a file sharing program and the jist of it is that there is one main server which all clients connect to. However, the clients are the machines hosting the files so when one client requests a file from another, it must create a connection with it. When the client initially connects with the main server I get it's IP and port (I think) with:
int client_len = sizeof(client);
int new_sd = accept(sd, (struct sockaddr *)&client, &client_len);
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(client.sin_addr), str, INET_ADDRSTRLEN);
//printf("%s\n", str);
int port = (int) ntohs(client.sin_port);
//printf("Port is: %d\n", (int) ntohs(client.sin_port));
The printf's give me 127.0.0.1 and 40XXX. The main server is using 127.0.0.1 and port 3000. So I'm pretty sure I have the correct client IP and port BUT when I try to set up a connection between 2 clients using 127.0.0.1 and 40XXX, it does not work. The connect function keeps returning an error. Here's the code trying to establish a connection between two clients:
if ((cd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "Can't creat a socket\n");
exit(1);
}
bzero((char *)&cServer, sizeof(struct sockaddr_in));
cServer.sin_family = AF_INET;
cServer.sin_port = htons(cPort);
if (inet_pton(AF_INET, cAddress, &cServer.sin_addr) == -1) {
printf("inet_pton error occured\n");
exit(1);
}
/* Connecting to the server */
if (connect(cd, (struct sockaddr *)&cServer, sizeof(cServer)) == -1) {
fprintf(stderr, "Can't connect to server\n");
exit(1);
}
cPort is an int while cAddress is a char array.
Here's the code from the client attempting to create a connection for incoming connections. The code to get the IP Address and port return 0.0.0.0 and 0 respectively.
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
fprintf(stderr, "Can't creat a socket\n");
exit(1);
}
/* Bind an address to the socket */
bzero((char *)&clientServer, sizeof(struct sockaddr_in));
clientServer.sin_family = AF_INET;
clientServer.sin_port = 0;
clientServer.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&clientServer, sizeof(clientServer)) == -1){
fprintf(stderr, "Can't bind name to socket\n");
exit(1);
}
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(clientServer.sin_addr), str, INET_ADDRSTRLEN);
printf("%s\n", str);
int clientServerPort = (int) ntohs(clientServer.sin_port);
printf("Port is: %d\n", (int) ntohs(client.sin_port));
/* queue up to 10 connect requests */
listen(sockfd, 10);
All help is greatly appreciated!