[Socket][网络编程]程序范例:Linux下连接WEB服务器

作者: lesca 分类: HTTP,SOCKET,Ubuntu,Web 发布时间: 2011-03-01 16:43

昨天试着在Ubuntu 下用C语言写了一个客户端,用来向WEB服务器上交请求并取回响应报文。
同时,这也是一个通用的基于IPv4的客户端程序例程。

[cpp]
/* socket test on linux main file.
*
* Author: Lesca<http://lesca.me>
* License: GPL
*
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
int socketfd;
int len;
struct sockaddr_in address;
int result;
const char request[] = "GET / HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n";
char buf;

// 定义套接字类型并命名套接字
socketfd = socket(AF_INET, SOCK_STREAM, 0);
perror("socketfd");
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(80); // 将短整型转为网络字节序
len = sizeof(address);

// 将这个套接字连接到服务器
result = connect(socketfd, (struct sockaddr *)&address, len);
if(result == -1) {
perror("oops: client1");
exit(1);
}
perror("connect");

// Linux中套接字的读写和文件没有区别(真是方便那!!)
write(socketfd, request, strlen(request));
perror("write");
while(read(socketfd, &buf, 1))
{
putchar(buf);
}

// 关闭套接字
close(socketfd);
exit(0);
}
[/cpp]

HTTP请求报文

GET / HTTP/1.1
Host: api		// 这是笔者机器上的一个虚拟主机的名字
Connection: close

HTTP应答报文
[html]
HTTP/1.1 200 OK
Date: Tue, 01 Mar 2011 08:45:42 GMT
Server: Apache/2.2.14 (Ubuntu)
Last-Modified: Mon, 21 Feb 2011 05:31:27 GMT
ETag: "58d054-1b9-49cc42cdc49c0"
Accept-Ranges: bytes
Content-Length: 441
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Lesca’s References, documentations, specifications and APIs</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

</head>
<frameset cols="150,*">
<frame name="left" src="left.html">
<frame name="right" src="right.html">
<noframes>
Your broswer doesn’t support frames<br/>
</noframes>
</frameset>
</html>
[/html]
References:
[1] Neil Matthew, Richard Stones – Beginning Linux Programming 4th Edition

版权声明

本文出自 Lesca 技术宅,转载时请注明出处及相应链接。

本文永久链接: https://www.lesca.cn/archives/connect-to-web-server-with-socket-on-ubuntu.html

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!