【问题标题】:Getting 400 Bad Request when trying to connect to website via winsock socket尝试通过 winsock 套接字连接到网站时收到 400 Bad Request
【发布时间】:2015-08-16 19:31:27
【问题描述】:

我做了一个插座,我已经慢慢添加了大约一个星期,但我遇到了一个问题。我在本地 127.0.0.1 ip 地址上设置了一个端口,以允许我连接到自己的计算机,当我收到计算机的响应时,它显示“400 Bad Request。请求格式错误。”。我认为这与我通过send(); 函数发送的http 标头信息有关。 sendbuf 包含要发送的标头信息。这是我的代码:

#include <windows.h>
#include <winsock2.h>
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define SCK_VERSION2 0x0202
#define DEFAULT_BUFLEN 2000
#define DEFAULT_PORT 27015

namespace Globals{
    extern string input = "";
}
using namespace Globals;

void USERNAME() {
    do {
            printf("USERNAME: \t");
            getline(cin, input);
            if ( input == "User Name" ) {
                    break;
             }
        } while(true);

}

void PASSWORD() {
    do {
        printf("PASSWORD: \t");
    getline(cin, input);
    if ( input == "Password" ) {
        break;
    }
    USERNAME();
    } while(true);
}

int whole() {

    USERNAME();
    PASSWORD();

    //----------------------
    // Declare and initialize variables.
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket = INVALID_SOCKET;
    struct sockaddr_in clientService;

    char name[500] = "";
    char ipADDRESS[500] = "";
    char sPORT[500] = "";

    sockaddr_in sName;
    int sNameSize =  sizeof(sName);

    char *sendbuf = "GET /TR HTTP/1.1 \nHost: net.tutsplus.com \nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729) \nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 \nAccept-Language: en-us,en;q=0.5 \nAccept-Encoding: gzip,deflate \nAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 \nKeep-Alive: 300 \nConnection: keep-alive \nCookie: PHPSESSID=r2t5uvjq435r4q7ib3vtdjq120 \nPragma: no-cache \nCache-Control: no-cache";
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;                                    //208.109.181.178
    int WSAERROR = WSAGetLastError();
    //system("color 04");
    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
      printf("WSAStartup failed: %d\n", iResult);
      return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %i\n", WSAGetLastError() );
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.

    printf("IP ADDRESS: \n");
    cin >> ipADDRESS;
    printf("PORT: \n");
    cin >> sPORT;
    u_short PORT = strtoul(sPORT, NULL, 0);
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr(ipADDRESS);                            //74.125.196.191
    clientService.sin_port = htons(PORT);

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        printf("Unable to connect to server: %i\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    //----------------------
    //Get local host name
    iResult = gethostname(name, sizeof(name));
    if (iResult == NO_ERROR) {
        printf("Host Name: %s\n", name);
    }
    else if (iResult == SOCKET_ERROR) {
        printf("Could not resolve host name: %i", WSAGetLastError());
    }

    //------------------------
    //Get peer name
    iResult = getpeername(ConnectSocket, (struct sockaddr*)&sName, &sNameSize);
    if (iResult == NO_ERROR)
        printf("Peer Name: %s\n", inet_ntoa(sName.sin_addr));
    else if (iResult == SOCKET_ERROR)
        printf("Could not get peer name: %i\n", WSAGetLastError());

    //-------------------------
    // Send an initial buffer
    iResult = send( ConnectSocket, sendbuf, (int)strlen(sendbuf), 0 );
    if (iResult == SOCKET_ERROR) {
        printf("send failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }
    else
        printf("Bytes Sent: %i\n", iResult);

    //-----------------------------
    // shutdown the connection since no more data will be sent
    iResult = shutdown(ConnectSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 ) {
            printf("Bytes received: %d\n", iResult); //printf("Bytes received: %d\n", iResult);
            printf("From server: %s\n", recvbuf);
        }
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else if (WSAERROR == WSAETIMEDOUT)
            printf("recv failed: WSAETIMEDOUT\n");
        printf("Do you want to disconnect? (Y/N) \n");
        cin >> input;
        if ( input == "Y"||"y" ) {
            break;
        }
        else if ( input == "N"||"n" ) {
            break;
        }
    } while( iResult > 0 );

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    system("PAUSE");
    return 0;
}

int main() {
    do {
        whole();
    } while( input != "N"||"n" );

}

【问题讨论】:

  • 请求和响应的详细信息会有所帮助,也许是curl -v
  • HTTP/1.1 400 Bad Request Content-Type: text/html; charset=us-ascii Server: Microsoft-HTTPAPI/2.0 Date: Sun, 16 Aug 2015 19:40:33 GMT Connection: close Content-Length: 311 &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/str ict.dtd"&gt; &lt;HTML&gt;&lt;HEAD&gt;&lt;TITLE&gt;Bad Request&lt;/TITLE&gt; &lt;META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"&gt;&lt;/HEAD&gt; &lt;BODY&gt;&lt;h2&gt;Bad Request&lt;/h2&gt; &lt;hr&gt;&lt;p&gt;HTTP Error 400. The request is badly formed.&lt;/p&gt; &lt;/BODY&gt;&lt;/HTML&gt; 是它发送给我的。
  • “设置端口”是什么意思?该请求是否有效取决于您的服务器。
  • 我对套接字编程很陌生,我对这些东西的了解不多,所以请耐心等待。我第一次运行程序窗口时询问我是否想在防火墙中创建一个例外。所以在那之后我能够连接到一个特定的端口。我如何找出它正在使用什么服务器或没有使用什么服务器?

标签: c++ sockets http winsock2


【解决方案1】:

我想通了,在sendbuf 我输入了一个无效的主机名。呵呵

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 2017-11-06
    • 2017-12-31
    • 2016-09-10
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多