无法在 C++ 的套接字编程中连接,而在 python 中,它可以工作

Not able to connect in socket programming in C++ whereas in python, it works

我在python有一段代码。它与客户端Socket编程有关。我想从“www.rtk2go.com”获取 NTRIP 数据。 python写的代码效果很好,达到目的。

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

我想用 C++ 代码实现同样的事情,在看了一些在线教程之后,我用 C++ 编写了以下代码(我对 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] = '[=12=]';
    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;
}

但连接方法总是 returns -1(在 C++ 中)。知道我做错了什么吗?

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

表示sockfd不是0就是1,不是有效的socket。

改为这样做:

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