套接字http请求失败

时间:2014-01-29 11:06:49

标签: c sockets http ubuntu

我正在编写简单的c程序发送http请求,加载的USB调制解调器设备(cdc_ether)在ubuntu机器上具有带有ethx接口的192.168.0.144 ip地址。我能够成功发送请求http请求是失败。由于设备是由http请求控制管理控制的。

定义BUFFSIZE 512

define MAXBUF 512

void error(char *msg);

int serverSocket;

int i,n = 0;

size_t bWritten, bTotal;

struct sockaddr_in serverAddr;

struct hostent *hostptr;

const int optVal = 1;

const socklen_t optLen = sizeof(optVal);

char buffer[BUFFSIZE];

char *set_cmd_post="/goform/goform_set_cmd_process";

char *host="192.168.0.1";

char sendline[BUFFSIZE + 1]={0};

char recvline[BUFFSIZE + 1]={0};

char *post_str_connect="goformId=CONNECT_NETWORK\r\n";


int main (int argc, const char * argv[]) {

    int j=0;

    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(80);
    serverAddr.sin_addr.s_addr = inet_addr("192.168.0.1");


    snprintf(sendline, MAXBUF,
             "POST %s HTTP/1.1\r\n"  // POST or GET, both tested and works. Both HTTP 1.0 HTTP 1.1 works, but sometimes
             "Host: %s\r\n"     // but sometimes HTTP 1.0 works better in localhost type
             "Connection: Keep-alive\r\n\r\n"
             "Content-type: application/x-www-form-urlencoded\r\n"
             "Content-length: %d\r\n\r\n"
             "%s", set_cmd_post, host, (unsigned int)strlen(post_str_connect), post_str_connect);
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    if (serverSocket < 0)
        error("socket()");
    int rtn = setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (void*) &optVal, optLen);

    if (connect(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
        error("connect()");

    printf("connect to server success \n");

    if (send(serverSocket, sendline, strlen(sendline),0)>= 0)
    {
        printf("write success \n");

        do
        {

            n = recv(serverSocket, recvline, sizeof(recvline), 0);
            if (n > 0 )
                printf("%s", recvline);
        }
        while ( n > 0 );

    }

}

输出:

POST / goform / goform_set_cmd_process HTTP / 1.0

User-Agent:rndis_socket

主持人:192.168.0.1

接受: /

内容长度:24

内容类型:application / x-www-form-urlencoded

goformId = CONNECT_NETWORK

HTTP / 1.0 200 OK

服务器:GoAhead-Webs

Pragma:no-cache

缓存控制:无缓存

内容类型:text / html

{ “结果”: “失败”}

1 个答案:

答案 0 :(得分:0)

是的,它现在正在使用wireshark来解决这个问题。

snprintf(sendline,MAXBUF,

“POST%s HTTP / 1.1 \ r \ n”

“用户代理:%s \ r \ n”

"Host: %s\r\n"     

“接受: / \ r \ n”

"Content-length: %d\r\n"

“内容类型:application / x-www-form-urlencoded \ r \ n \ r \ n”

“%s”,set_cmd_post,agent,host,(unsigned int)strlen(post_str_connect),post_str_connect)

char * post_str_connect =“goformId = CONNECT_NETWORK”;

由于