Linux下http協議實現 C

2021-06-20 21:29:11 字數 2820 閱讀 2842

#

include

#include

#include

<

string

.h>

#include

#include

socket

.h>

#include

<

errno

.h>

#include

#include

#include

#include

#include

#include

<

ctype

.h>

int main(

int argc,

char

*argv)

portnumber=80;

strcpy

(host_addr,argv[1]);

if((host=

gethostbyname

(argv[1]))

==null

)/*取得主機ip位址*/if(

(sockfd=

socket

(af_inet

,sock_stream

,0))==

-1)/*建立socket連線*/

/* 客戶程式填充服務端的資料 */

bzero(

&server_addr,

sizeof

(server_addr));

server_addr.sin_family=

af_inet

;server_addr.sin_port=

htons

(portnumber)

;server_addr.sin_addr=*(

(struct

in_addr

*)host-

>h_addr)

;/* 客戶程式發起連線請求 */if(

connect

(sockfd,

(struct

sockaddr*)

(&server_addr)

,sizeof

(struct

sockaddr))

==-1)/*連線***/

;/*準備request,將要傳送給主機*/

/*取得真實的檔名*/

strcpy

(local_file,

"index.html");

/*傳送http請求request*/

send

= 0;totalsend = 0;

nbytes=

strlen

(request)

;while

(totalsend < nbytes)

totalsend+

=send

;printf

("%d bytes send ok!\n"

, totalsend);}

fp =

fopen

(local_file,

"a");if

(!fp)

printf

("\nthe following is the response header:\n");

i=0;

/* 連線成功了,接收http響應,response */

while

((nbytes=

read

(sockfd,buffer,1))=

=1)else

}fclose

(fp)

;/* 結束通訊 */

close

(sockfd)

;exit

(0);}

1    struct hostent *gethostbyname(const char *name);

struct hostent ;  

#define h_addr h_addr_list[0]           /*在h-addr-list中的第乙個位址*/

我們一般用的也就第乙個位址

struct sockaddr_in ;

這裡也提下 struct sockaddr

這個是描述sock 位址資訊的,和上面的結構大小一樣,可以相互轉換

struct sockaddr

3 我們和伺服器連上之後,就可以向伺服器傳送請求了

write(sockfd, char *, size);

內容就是:get /%s http/1.1\r\naccept: */*\r\naccept-language: zh-cn\r\n\user-agent: mozilla/4.0 (compatible; msie 5.01; windows nt 5.0)\r\n\

host: %s:%d\r\nconnection: close\r\n\r\n

具體是由其協議定的,我也還不是很清楚

4 伺服器響應,就會發來資訊頭+ 實際頁面的資訊, 這個中間是有4個("\r"或"\n")進行分開的。

Linux下http協議實現

include include include string h include include socket h include errno h include include include include include include ctype h int main int argc,ch...

Linux下http協議實現

include include include string h include include socket h include errno h include include include include include include ctype h int main int argc,ch...

http協議簡析及C 實現HTTP請求

http是超文字傳輸協議,無狀態協議 不同批次無法相互識別 無連線協議,工作在應用層,用於完成從全球資訊網伺服器傳輸超文字到本地瀏覽器的傳輸協議,完成了文件的快速傳輸,還能確定傳輸文件的哪一部分,以及控制哪一部分內容首先顯示。整個http過程由請求和響應構成,a通常承載與tcp協議上。http完整流...