如何从 vc++ 查询 http 请求项目

发布于 2024-11-10 19:01:31 字数 4653 浏览 0 评论 0原文

我正在编写一个示例程序以从某个站点获取文件。 但它回复我文件未找到错误,我不知道如何制作 http 标头。 任何人都可以帮我写http头。

我正在尝试以这种方式打印 ip(printf("%s\n",ptr->ai_addr->sa_data);) 但不知道如何打印IP地址??,我这样做对吗??

我的代码是:-

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "80"

int __cdecl main(int argc, char **argv) 
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    char *sendbuf = "GET / HTTP/1.1[CRLF] Host: www.espncricinfo.com[CRLF]Connection: close[CRLF]User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)[CRLF]Accept-Encoding: gzip[CRLF]Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]Cache-Control: no-cache[CRLF]Accept-Language: de,en;q=0.7,en-us;q=0.3 \r\n";
    char buff[DEFAULT_BUFLEN],recvbuf[512]; 
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;

    // Validate the parameters
    if (argc != 1) {
        printf("usage: %s server-name\n", argv[0]);
        return 1;
    }

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    // Resolve the server address and port
    iResult = getaddrinfo("122.169.255.9",DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server

        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        printf("inside loop %s ",ptr->ai_addr->sa_data);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        printf("%d\n",ptr->ai_addrlen);
//      printf("%s\n",ptr->ai_addr->sa_family);
        printf("%s\n",ptr->ai_addr->sa_data);

        if (iResult == SOCKET_ERROR) {
            printf("socket error\n");
            printf("failed with error: %d\n", WSAGetLastError());
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }
    // Send an initial buffer
    char filepath[]="pakistan/content/current/story/517271.html";
    sprintf(buff,"GET %s\r\n",filepath);
    iResult = send( ConnectSocket,buff, (int)strlen(buff), 0 );
    if (iResult == SOCKET_ERROR)
    {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

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

    do 
    {
        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        //if ( iResult > 0 ) printf("Bytes received: %d\n", iResult);
         if ( iResult > 0 )
         {
            printf("Bytes received: %d\n", iResult);
            printf("%s",recvbuf);
         }
         else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError()); 

    } while( iResult>0 );

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}

I am writing a sample program to get a file from some site.
but it is replying me file not found errors,i dont know how to make an http header.
anyone help me in writing http headers.

AND i am trying to print the ip in this way(printf("%s\n",ptr->ai_addr->sa_data);)
but not getting it how to print ip address??,am i doing it right??

my code is:-

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>


// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "80"

int __cdecl main(int argc, char **argv) 
{
    WSADATA wsaData;
    SOCKET ConnectSocket = INVALID_SOCKET;
    struct addrinfo *result = NULL,
                    *ptr = NULL,
                    hints;
    char *sendbuf = "GET / HTTP/1.1[CRLF] Host: www.espncricinfo.com[CRLF]Connection: close[CRLF]User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)[CRLF]Accept-Encoding: gzip[CRLF]Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]Cache-Control: no-cache[CRLF]Accept-Language: de,en;q=0.7,en-us;q=0.3 \r\n";
    char buff[DEFAULT_BUFLEN],recvbuf[512]; 
    int iResult;
    int recvbuflen = DEFAULT_BUFLEN;

    // Validate the parameters
    if (argc != 1) {
        printf("usage: %s server-name\n", argv[0]);
        return 1;
    }

    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory( &hints, sizeof(hints) );
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    // Resolve the server address and port
    iResult = getaddrinfo("122.169.255.9",DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Attempt to connect to an address until one succeeds
    for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {

        // Create a SOCKET for connecting to server

        ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, 
            ptr->ai_protocol);
        printf("inside loop %s ",ptr->ai_addr->sa_data);
        if (ConnectSocket == INVALID_SOCKET) {
            printf("socket failed with error: %ld\n", WSAGetLastError());
            WSACleanup();
            return 1;
        }

        // Connect to server.
        iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
        printf("%d\n",ptr->ai_addrlen);
//      printf("%s\n",ptr->ai_addr->sa_family);
        printf("%s\n",ptr->ai_addr->sa_data);

        if (iResult == SOCKET_ERROR) {
            printf("socket error\n");
            printf("failed with error: %d\n", WSAGetLastError());
            closesocket(ConnectSocket);
            ConnectSocket = INVALID_SOCKET;
            continue;
        }
        break;
    }

    freeaddrinfo(result);

    if (ConnectSocket == INVALID_SOCKET) {
        printf("Unable to connect to server!\n");
        WSACleanup();
        return 1;
    }
    // Send an initial buffer
    char filepath[]="pakistan/content/current/story/517271.html";
    sprintf(buff,"GET %s\r\n",filepath);
    iResult = send( ConnectSocket,buff, (int)strlen(buff), 0 );
    if (iResult == SOCKET_ERROR)
    {
        printf("send failed with error: %d\n", WSAGetLastError());
        closesocket(ConnectSocket);
        WSACleanup();
        return 1;
    }

    printf("Bytes Sent: %ld\n", iResult);

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

    do 
    {
        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        //if ( iResult > 0 ) printf("Bytes received: %d\n", iResult);
         if ( iResult > 0 )
         {
            printf("Bytes received: %d\n", iResult);
            printf("%s",recvbuf);
         }
         else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed with error: %d\n", WSAGetLastError()); 

    } while( iResult>0 );

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();

    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

悲凉≈ 2024-11-17 19:01:31

如果您收到“找不到文件”的消息,那是因为您请求的文件无法找到。

也许可以尝试使用前导斜杠的 "/pakistan/content/current/story/517271.html"

你的 HTTP 协议说明符在哪里?

写:

GET path HTTP/1.0

(1.0因为你可能不想搞乱虚拟主机;1.1如果你必须的话)

为什么你在尝试读取之前关闭套接字......?我知道你只关闭“发送”管道,但它仍然看起来很奇怪。

也许您应该使用预先建立的库来为您完成此操作。


http://122.169.255.9/ 上的网络服务器似乎并未实际工作。也许首先使用已知良好的服务器(例如 http://www.google.com)进行测试。

If you're getting "File Not Found", it's because you're requesting a file that can't be found.

Perhaps try "/pakistan/content/current/story/517271.html", with the leading slash.

And where's your HTTP protocol specifier?

Write:

GET path HTTP/1.0

(1.0 because you probably don't want to mess about with virtual hosts; 1.1 if you have to)

And why do you shutdown the socket before attempting to read from it...? I know you only shutdown the "send" pipe, but it still seems odd.

Perhaps you ought to use a pre-established library to do this for you.


The webserver at http://122.169.255.9/ doesn't appear to actually work. Perhaps test with a known-good server like http://www.google.com first.

成熟的代价 2024-11-17 19:01:31

如果您要使用 Microsoft Windows 函数,WinInet 中的 HTTP 函数要容易得多。请参阅 HttpOpenRequest/HttpSendRequest/HttpQueryInfo/InternetReadFile

If you're going to use Microsoft Windows functions, the HTTP functions in WinInet are a lot easier. See HttpOpenRequest/HttpSendRequest/HttpQueryInfo/InternetReadFile

私野 2024-11-17 19:01:31

如果您不想重新发明轮子,请使用像 libcurl 这样的库。

If you don't want to reinvent the wheel, use a library like libcurl.

楠木可依 2024-11-17 19:01:31

除了 Tomalak Geret'kal 之外,

您还需要使用 HTTP/1.0,除非您想要检查分块内容以及 HTTP 1.1 可能向您抛出的更多内容。

安装 Wireshark 并记录请求。你就会看到出了什么问题。

我不知道 [CRLF] 被自动更改为 \r\n

In addition to Tomalak Geret'kal

You'll want to use HTTP/1.0 unless you want to check for chunked content and more stuff HTTP 1.1 can throw at you.

Install Wireshark and log the requests. You'll see what is wrong.

I'm not aware of [CRLF] being automatically changed to \r\n

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文