简体   繁体   中英

Socket in c TCP how do i test connection?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM