0

For a school project I have to use sockets to create a server, I think I managed to do it but I am supposed to use Telnet to test it, and whenever I try I get

telnet: connect to address 0.0.0.0: Connection refused

So i guess it is with the IP that I'm wrong.

The simplified version of my code that should still work for one connection is

int main(int argc , char *argv[])
{
    int sock;
    int fd = 0;
    int err = 0;
    struct sockaddr_in sock_data;
    socklen_t addr_size;
    char *path;

    path = get_current_dir_name();

    if (argc == 2)
        printf("%s", Usage);

    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1) {
        printf("Could not create socket");
        return (84);
    }

    memset(&sock_data, 0, sizeof(struct sockaddr_in));
    sock_data.sin_family = AF_INET;
    sock_data.sin_port = htons(5133);
    sock_data.sin_addr.s_addr = htonl(INADDR_ANY);
    printf("%s, %s, %s\n", path, sock_data.sin_addr, inet_ntoa(sock_data.sin_addr));

    if (bind(sock, (const struct sockaddr *) &sock_data, sizeof(sock_data)) == -1)
        printf("Error with binding\n");

    if (listen(sock, LISTEN_BACKLOG) == -1)
        printf("Error with listen");

    addr_size = sizeof(struct sockaddr_in);
    err = accept(sock, (struct sockaddr *) &sock_data, &addr_size);

    while ((sock = accept(sock, NULL, NULL)) < 0)
        err = 0;
    return 84;
}

I saw this link: TCP sockets in c that was quite clear but I still don't get how I am supposed to test my program

And the more I work on it the more I am convinced that I must have made a stupid mistake.

So do you know where I went wrong?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • 1
    On a side note, `accept(sock, (struct sockaddr *) &sock_data, &addr_size)` needs to be moved inside the `while` loop (or removed, since `accept(sock, NULL, NULL)` already inside the loop will suffice). But, you are not `close()`'ing any of the descriptors returned by `accept()`. And, in `sock = accept(sock, NULL, NULL)` you are reassigning `sock` thus losing access to your listening socket (which you are not `close`'ing(), either). You need to use separate descriptor variables for your listening and accepted sockets. – Remy Lebeau May 07 '20 at 21:23
  • Thanks! i am new to using sockets, this is quite helpful! don't hesitate if you have other advices ;) – Aldric Liottier May 08 '20 at 21:01

1 Answers1

3

In your Telnet command you missed a port. The commamd should be like a

telnet system_ip port

For example

telnet 192.168.1.1 5631
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39