带有C的HTTP请求;调用PHP文件并读取echo文本输出/响应

时间:2016-08-05 05:27:58

标签: php c httprequest

我只想通过在C中调用它来读取PHP文件中的响应。

目前我有以下PHP脚本和C程序:

PHP文件:

<?php echo "successful"; ?>

C代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#include <netinet/tcp.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>


int socket_connect(char *host, in_port_t port){
    struct hostent *hp;
    struct sockaddr_in addr;
    int on = 1, sock;

    if((hp = gethostbyname(host)) == NULL){
        herror("gethostbyname");
        exit(1);
    }
    bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
    addr.sin_port = htons(port);
    addr.sin_family = AF_INET;
    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int));

    if(sock == -1){
        perror("setsockopt");
        exit(1);
    }

    if(connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1){
        perror("connect");
        exit(1);

    }
    return sock;
}

#define BUFFER_SIZE 1024

int main(int argc, char *argv[]){
    int fd;
    char buffer[BUFFER_SIZE];

    fd = socket_connect("myserver.bplaced.net", 80);
    write(fd, "GET /MySQLadmin/myscript.php HTTP/1.0\r\n\r\n", strlen("GET /MySQLadmin/myscript.php HTTP/1.0\r\n\r\n")); // write(fd, char[]*, len);
    bzero(buffer, BUFFER_SIZE);

    while(read(fd, buffer, BUFFER_SIZE - 1) != 0){
        fprintf(stderr, "%s", buffer);
        bzero(buffer, BUFFER_SIZE);
    }

    shutdown(fd, SHUT_RDWR);
    close(fd);

    return 0;
}

到目前为止,我可以联系服务器但是当我读取BUFFER时,我会收到以下内容,但不会收到回音文本。

控制台中的输出:

HTTP/1.1 302 Found
Date: Fri, 05 Aug 2016 05:21:14 GMT
Server: Apache/2.4
Location: http://www.bplaced.net/404
Content-Length: 271
Connection: close
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved <a href="http://www.bplaced.net/404">here</a>.</p>
<hr>
<address>Apache/2.4 Server at default Port 80</address>
</body></html>

Process returned 0 (0x0)   execution time : 0.126 s
Press any key to continue.

也许我在某个地方有一个错字但找不到它。

请帮忙

0 个答案:

没有答案