Bringing programs across the internet age-use the C language to get Baidu source code

Source: Internet
Author: User

When I had been in the standalone world for several months, I followed the trend of the times and formally entered the network programming era. Learning a new technology is always an exciting thing. However, it is undoubtedly difficult to find a good learning tutorial. Baidu and Google searched countless times and finally entered the Winsock door, I will release my experiences in Windows Network Programming for you to learn. I am also a newbie. If you have any mistakes in the blog post, please submit them to help me correct the mistakes.

If you have learned WinSock programming before, read this article.ArticleIt will be very easy. It doesn't matter if you haven't learned it. This blog will explain it in detail. OK. Skip to the topic.

 

1. Before using any Winsock function, you must add the winsock2.h and ws2_32.lib files to the header file.

 
# Include <winsock2.h># PragmaComment (Lib, "ws2_32.lib ")

At the same time, we should note that the winsock2.h header file must be placed on the windows. h header file. Otherwise, errors may occur during compilation.

2. Before calling any Winsock function, you must use the wsastartup function to initialize the Winsock service.

 
IntWsastartup (word wversionrequested, lpwsadata)

(1) wversionrequested: A Word (dubyte) type value. In the highest version of Windows Sockets, it can be used by callers. The higher-level bytes specify the minor version (revision) number, and the lower-level bytes specify the primary version number. Makeword)

(2) lpwsadata refers to the pointer to the wsadata data structure, which is used to receive details about the implementation of Windows Sockets.

3. After we call the wsastartup function, we can call other Winsock functions. Use the wsasocket function to create a socket bound to the specified service provider.

 
Wsasocket (IntAF,IntType,IntProtocol, lpwsaprotocol_infow lpprotocolinfo, group G, DWORD dwflags );

(1) af: An Address Family specification. We use af_inet.

(2) type: the type description of the new socket. We use sock_stream, that is, TCP

(3) Protocol: The specific protocol used by the socket. If the caller does not want to specify the protocol, the value is set to 0.

(4) lpprotocolinfo: a pointer to the protocol_info structure, which defines the features of the interfaces created. If this parameter is not zero, the first three parameters (AF, type, Protocol) are ignored.

(5) G: reserved for future socket groups. The identifier of the Set interface group.

(6) dwflags: Set interface attribute description.

Generally, we use the first three, and all the following are null. If the request succeeds, a socket is returned. If an error is returned, socket_error is returned.

4. We use the connect function to connect to the website we specified.

 
Connect (socket s,Const StructSockaddr far * Name,IntNamelen );

(1) S: Socket descriptor, that is, the socket returned by the wsasocket function.

(2) Name: A sockaddr type, but we generally use the sockaddr_in type, that is, the IP address and port we need to connect.

(3) namelen: the length of the sockaddr struct.

Sockaddr_in ipconfig; hostent*Iphost;Char* Url ="Baidu.com";If(Iphost = gethostbyname (URL ))! =Null) ipconfig. sin_addr.s_un.s_addr= Inet_addr (inet_ntoa (*((StructIn_addr *) iphost-> h_addr_list [0]) Ipconfig. sin_port= Htons (80); Ipconfig. sin_family= Af_inet;

Let's look at another blog post: Use the C language to get the IP address of the specified domain name

 

5. After we connect, we need to send the HTTP header information, as shown below:

 
Char* Httpheader ="GET/index.html \ r \ naccept: Application/JavaScript, */*; q = 0.8 \ r \ nhost: Baidu.com \ r \ nconnection: keep-alive \ r \ n"

Then use the send function to send it to the host.

 
Send (sock, httpheader, strlen (httpheader) +1,0)

6. after sending the message, we need to use the Recv function to receive the information returned from the server. The first response is the HTTP header returned from the server. We can see whether the request is successful, then, the returned result is the webpage'sSource code:

 Int I = 0 , Check, err = 0  ; Char Recvchar [ 100  ];  Char Recvcda [ 500  ];  If (Recv (sock, recvcda, 500 , 0 ) = Socket_error) {fprintf (stderr,  "  An error occurred while returning the information.Code: % D  "  , Wsagetlasterror (); System ( "  Pause  "  );  Return   1  ;} Printf (  "  The HTTP header returned by the server: % s \ n  "  , Recvcda); memset (recvchar,  '  \ 0  ' , 101  );  While (Check = Recv (sock, recvchar, Sizeof (Recvchar ), 0 ))! = Socket_error ){  If (Check < 100  ) Err = 1  ; Printf (  "  % S  "  , Recvchar); memset (recvchar,  0 , 100 );  If (ERR = 1  )  Break  ; I ++ ;} 

OK. The following is a complete code for obtaining Baidu source code:

# Include <stdio. h> # Include < String. h > # Include <Winsock2.h> # Include <Windows. h> # Pragma Comment (Lib, "ws2_32.lib ")Using   Namespace  STD;  Char * Urlip ( Char * URL );  Int Main ( Int Argc, Char * Argv []) {sockaddr_in url_ipconfig = { Sizeof  (Sockaddr_in )};  Char *Sendchar; wsadata wsada; socket sock;  Char IP [ 20  ];  Char Sendstring [ 100  ];  Char Recvchar [ 100  ];  Char Recvcda [ 500  ];  If (Wsastartup (makeword ( 2 , 2 ), & Wsada) = Socket_error) {fprintf (stderr,  "  An error occurred while initializing wsastartup. Error code: % d  "  , Wsagetlasterror (); System (  "  Pause  "  );  Return   1  ;}  If (Sock = wsasocket (af_inet, sock_stream,0 , Null, null, 0 ) = Socket_error) {fprintf (stderr,  "  An error occurred while initializing wsastartup. Error code: % d  "  , Wsagetlasterror (); System (  "  Pause  "  );  Return   1  ;} Strcpy (IP, urlip (  " Baidu.com  "  ); Url_ipconfig.sin_family = Af_inet; url_ipconfig.sin_port = Htons ( 80  ); Url_ipconfig.sin_addr.s_un.s_addr = Inet_addr (IP );  If (Connect (sock, (sockaddr *) & url_ipconfig, Sizeof (Url_ipconfig) = Socket_error) {fprintf (stderr,  "  Failed to connect to the server. Error code: % d "  , Wsagetlasterror (); System (  "  Pause  "  );  Return   1  ;} Strcpy (sendstring,  "  GET/index.html HTTP/1.1 \ r \ naccept: Application/JavaScript, */*; q = 0.8 \ r \ nhost: Baidu.com \ r \ nconnection: keep-alive \ r \ n  "  );  If (Send (sock, sendstring, strlen (sendstring) +1 , 0 ) = Socket_error) {fprintf (stderr,  "  Failed to send get package, error code: % d \ n  "  , Wsagetlasterror (); System (  "  Pause  "  );  Return   1  ;} Memset (recvcda,  ' \ 0  ' , 500  );  If (Recv (sock, recvcda, 500 , 0 ) = Socket_error) {fprintf (stderr,  "  Error Code returned: % d  "  , Wsagetlasterror (); System (  "  Pause  " );  Return   1  ;} Printf (  "  % S \ n  "  , Recvcda );  Int I = 0 , Check, err = 0  ; Memset (recvchar,  '  \ 0  ' , 101 );  While (Check = Recv (sock, recvchar, Sizeof (Recvchar ), 0 ))! = Socket_error ){  If (Check < 100  ) Err = 1  ; Printf (  "  % S  "  , Recvchar); memset (recvchar, 0 , 100  );  If (ERR = 1  )  Break  ; I ++ ;} System (  "  Pause  "  );  Return   0  ;} Char * Urlip ( Char * URL) {hostent * Iphost;  Char Ipconfig [ 20  ];  Char IP [ 20  ];  If (Iphost = gethostbyname (URL ))! = Null) {memcpy ( & IP, inet_ntoa (*(( Struct In_addr *) iphost-> h_addr_list [0 ]), 20  );}  Return  IP address ;} 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.