Home > Blockchain >  Not able to connect in socket programming in C whereas in python, it works
Not able to connect in socket programming in C whereas in python, it works

Time:02-01

I have a piece of code in python. It is related to client Socket programming. I want to get the NTRIP data from "www.rtk2go.com". The code written in python works well and serves the purpose.

import socket
import base64

server = "www.rtk2go.com"
port = "2101"
mountpoint = "leedgps"
username = ""
password = ""


def getHTTPBasicAuthString(username, password):
    inputstring = username   ':'   password
    pwd_bytes = base64.standard_b64encode(inputstring.encode("utf-8"))
    pwd = pwd_bytes.decode("utf-8").replace('\n', '')
    return pwd


pwd = getHTTPBasicAuthString(username, password)

print(pwd)

header = "GET /{} HTTP/1.0\r\n".format(mountpoint)   \
         "User-Agent: NTRIP u-blox\r\n"   \
         "Accept: */*\r\n"   \
         "Authorization: Basic {}\r\n".format(pwd)   \
         "Connection: close\r\n\r\n"

print(header)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, int(port)))
s.sendto(header.encode('utf-8'), (server, int(port)))
resp = s.recv(1024)
try:
    while True:
        try:
            data = s.recv(2048)
        except:
            pass

finally:
    s.close()

I wanted to implement the same thing in c code and after going through few online tutorials, I wrote the following code in C (I am very new to C )

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>

using namespace std;
#define SIZE 1000
#define PORT 2101

string base64Encoder(string input_str, int len_str) {

    char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /";

    char *res_str = (char *) malloc(SIZE * sizeof(char));

    int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
    int i, j, k = 0;

    for (i = 0; i < len_str; i  = 3) {
        val = 0, count = 0, no_of_bits = 0;

        for (j = i; j < len_str && j <= i   2; j  ) {
            val = val << 8;
            val = val | input_str[j];
            count  ;
        }

        no_of_bits = count * 8;
        padding = no_of_bits % 3;

        while (no_of_bits != 0) {
            // retrieve the value of each block
            if (no_of_bits >= 6) {
                temp = no_of_bits - 6;

                // binary of 63 is (111111) f
                index = (val >> temp) & 63;
                no_of_bits -= 6;
            } else {
                temp = 6 - no_of_bits;

                // append zeros to right if bits are less than 6
                index = (val << temp) & 63;
                no_of_bits = 0;
            }
            res_str[k  ] = char_set[index];
        }
    }

    for (i = 1; i <= padding; i  ) {
        res_str[k  ] = '=';
    }

    res_str[k] = '\0';
    string a = res_str;
    return a;

}


int main() {
    string input_str = ":";
    int len_str;

    len_str = input_str.length();
    string pwd = base64Encoder(input_str, len_str);
    string mountpoint = "leedgps";
    string header = "GET /"   mountpoint   " HTTP/1.0\r\n"   \
         "User-Agent: NTRIP u-blox\r\n"   \
         "Accept: */*\r\n"   \
         "Authorization: Basic "   pwd   "\r\n"   \
         "Connection: close\r\n\r\n";
    struct hostent *h;
    if ((h = gethostbyname("www.rtk2go.com")) == NULL) { // Lookup the hostname
        cout << "cannot look up hostname" << endl;
    }
    struct sockaddr_in saddr;
    int sockfd, connfd;
    sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
    if (sockfd) {
        printf("Error creating socket\n");
    }
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(2101);
    if(inet_pton(AF_INET, "3.23.52.207", &saddr.sin_addr)<=0) // 
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }
    cout << connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) << endl;


    return 0;
}

But the connect method always returns -1 (in C ). Any idea what am I doing wrong?

CodePudding user response:

sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;

means that sockfd is either 0 or 1, which is not a valid socket.

Do this instead:

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
    printf("Error creating socket\n");
}
  •  Tags:  
  • Related