使用Socket编程登录服务器



我正在尝试编写一个代码,连接我们的本地服务器,登录到该服务器上的网页并检索一些数据。我可以使用服务器IP和连接功能连接服务器。现在我需要登录一个接受以下格式的网页:

addUPI?function=login&user=user-name&passwd=user-password&host-id=xxxx&mode=t/z

我写了这样的东西:

int ret= send(sock,"addUPI?funcion...&mode=t",strlen("addUPI?funcion...&mode=t"),0);

但它不起作用。有人能帮我吗?

这不是实现HTTP的正确方法。首先,典型的HTTP生命周期看起来像这样(非常缩写):

...Connect
>>> GET / HTTP/1.0
>>> Host: localhost
>>> Referrer: http://www.google.com
>>>
<<< HTTP/1.0 200 OK
<<< Date: Wed, 08 Apr 2015 05:21:32 GMT
<<< Content-Type: text/html
<<< Content-Length: 20
<<< Set-Cookie: ...
<<<
<<< <html><h1>Hello World</h1></html>

这是假设没有重定向、SSL或其他神秘的协议发生。因此,只需写入上面指定的字符串,就会由于不遵守协议而导致连接关闭。

实际上,您可能想要使用像cURL这样的完全烘焙的HTTP库,它管理所有的协议需求。

我无耻地从curl网站上改编了这个例子:

#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
  CURL *curl;
  CURLcode res;
  curl = curl_easy_init(); 
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/addUPI?function=login&user=user-name&passwd=user-password&host-id=xxxx&mode=t");
    /* example.com is redirected, so we tell libcurl to follow redirection */ 
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    /* Perform the request, res will get the return code */ 
    res = curl_easy_perform(curl);
    /* Check for errors */ 
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %sn",
              curl_easy_strerror(res));
    /* always cleanup */ 
    curl_easy_cleanup(curl);
  }
  return 0;
}

最新更新