Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket error: connection refused - what am I doing wrong?

Tags:

c

linux

sockets

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) ...

like image 441
Kalec Avatar asked Jan 15 '13 18:01

Kalec


2 Answers

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()
like image 163
moooeeeep Avatar answered Oct 08 '22 17:10

moooeeeep


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
like image 30
Satish Avatar answered Oct 08 '22 17:10

Satish