【C程序文件:client.c】
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void)
{
// 建立套接字
struct sockaddr_in addr;
char buffer[1024];
char *request;
char *html;
int i;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket error\n");
exit(1);
}
printf("sockfd = %d\n", sockfd);
// 连接到服务器
addr.sin_family = AF_INET;
addr.sin_port = htons(80); // 端口号
addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
bzero(addr.sin_zero, sizeof(addr.sin_zero));
i = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
printf("connect = %d\n", i);
// 发送HTTP请求
request = "GET /test/simple.php HTTP/1.1\r\nHost: localhost\r\nAccept:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nAccept-Language:
en-US,en;q=0.5\r\nAccept-Encoding: gzip, deflate\r\nConnection:
keep-alive\r\nCache-Control: max-age=0\r\n\r\n";
write(sockfd, request, strlen(request));
// 读取服务器响应内容
bzero(buffer, sizeof(buffer));
i = read(sockfd, buffer, sizeof(buffer));
printf("read = %d\n", i);
puts("\nContent: ");
puts(buffer);
// 提取出HTML输出部分
for (html = buffer + 4; *html != '\0' && strncmp(html - 4, "\r\n\r\n", 4) != 0; html++);
printf("\nHTML(length=%ld): \n", strlen(html));
puts(html);
// 关闭套接字
close(sockfd);
return 0;
}
【Makefile】
client: client.c
gcc client.c -o client
【PHP页面:/var/www/html/test/simple.php】
<?php
echo 'test<br>';
echo date('Y-n-j H:i:s');
?>