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:
ECONNREFUSED No-one listening on the remote address.
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):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("localhost", 1234))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Your Answer is: You program is client and it need a server to connect. nc
command create server and your program can connect to it.
[root@mg0008 work]# nc -l 127.0.0.1 1234 &
[1] 25380
[root@mg0008 work]# ./socket
Give message: Hello
Hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With