Linux下http協議實現

2021-06-18 16:23:04 字數 2919 閱讀 4036

#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);

這個函式完成進行網域名稱和ip位址的轉換,返回的為:

struct hostent ;  

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

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

2   接下去就是socket 的建立,繫結,連線,我們想要連線,上面得到的ip位址是不行的,我們要使用伺服器的位址,具體資料結構如下:

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協議實現 C

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...

vb實現http協議

傳送文字和檔案資料 向屬性指派值時使用,位於賦值語句的左邊。syntax x.strtextfiled 5 mvarstrtextfiled vdata end property public property get strtextfiled as string 檢索屬性值時使用,位於賦值語句的右...