簡體   English   中英

無法在 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] = '\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;
}

但是 connect 方法總是返回 -1(在 C++ 中)。 知道我在做什么錯嗎?

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

表示sockfd為 0 或 1,這不是一個有效的套接字。

改為這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM