I’ve just started learning the basics of sockets (Linux). I tried my hand at a small example, but it doesn’t work and I have no idea what’s wrong.
I get a “Connection Refused” error message.
Here’s my code:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
int c;
c = socket(AF_INET, SOCK_STREAM, 0);
if (c < 0) {
printf("Error in creating socket! %s\n", strerror(errno));
return 1;
}
struct sockaddr_in server;
memset(&server, 0, sizeof(server));
server.sin_port = htons(1234);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1"); //local host
if (connect(c, (struct sockaddr *)&server, sizeof(server)) < 0) {
// Here is my error
printf("Error when connecting! %s\n",strerror(errno));
return 1;
}
while(1) {
char msg[100];
printf("Give message: ");
fgets(msg, sizeof(msg), stdin);
send(c, &msg, sizeof(msg), 0);
char resp[100];
recv(c, &resp, sizeof(resp), 0);
printf("Received: %s\n", resp);
}
close(c);
}
EDIT
Of course ! the error was actually in the server. I simply found it weired that the client sent the message, so I narrowed my view, didn’t even bother looking back at the server.
Since the error seems to be also in my server, I might end up asking another question and linking it here
Server was listening to (12345) …
According to the man page:
In order to provide a simple remote endpoint that accepts your connection and sends back the received data (echo server), you could try something like this python server (or to use netcat):