Search code examples
c++socketsconnection-refused

Connection refused while trying to retrieve html from http website using sockets in C


I have made a pretty simple http client which would retrieve html from http website and print it. But there seems to be some problem while using connect() function.Using perror() I found that it is giving connection refused error.

This is my code

#include <string.h>
#include <stdio.h>
#include <iostream>

#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>

#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    char *address;
    address = argv[1];

    int c_socket = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in URLaddress;

    URLaddress.sin_family = AF_INET;
    URLaddress.sin_port = htons(80);
    inet_pton(0,address,&URLaddress.sin_addr.s_addr);
    int con = connect(c_socket, (struct sockaddr*) &URLaddress, 
    sizeof(URLaddress));

    perror("error");

    return 0;
}

This is the input

151.101.13.5

This is the output

error: Connection refused

I am passing IP of website as input.

I have seen all other similar questions but didn't get any answer as how to fix this because this keeps happening with every website I try my program with. Please tell how to resolve this.


Solution

  • The following version of the code works on Windows/MSC:

    int test(void)
    {
        char *address;
        int c_socket, con;
        struct sockaddr_in URLaddress;
        char request[] = "GET / HTTP/1.1\r\n\r\n";
        char response[4096];
        WORD wVersionRequested;
        WSADATA wsaData;
    
        wVersionRequested = MAKEWORD( 2, 2 );
    
        address = "151.101.13.5";
    
        if (WSAStartup (wVersionRequested, &wsaData)!= 0) {
            printf("DLL not found\n");
            return -1;
        }
        if ((c_socket = socket(AF_INET, SOCK_STREAM, 0)) ==  INVALID_SOCKET ) {
            printf("socket error: %d\n", WSAGetLastError());
            return -1;
        }
    
        URLaddress.sin_family = AF_INET;
        URLaddress.sin_port = htons(80);
        URLaddress.sin_addr.s_addr= inet_addr(address);
        con = connect(c_socket, (struct sockaddr*) &URLaddress, sizeof(URLaddress));
    
        send(c_socket, request, strlen(request), 0);
        recv(c_socket, response, sizeof(response), 0);
        WSACleanup();
    
        printf ("%s\n",response);
    
        return 0;
    }
    

    The repsonse is:

    <title>Fastly error: unknown domain </title>
    </head>
    <body>
    <p>Fastly error: unknown domain: . Please check that this domain has been added to a service.</p>
    <p>Details: cache-fra19128-FRA</p></body></html>5¸`¡qu