#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>瀏覽器
int main(int argc, char *argv[]){
if(argc < 2){
puts("Usage: 2 filename.");
exit(1);
}
/*==========================================
* *****************建立socket**************
* ========================================*/
//建立套接字
int sock;
if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1){
fprintf(stderr, "Create socket error.\n");
exit(1);
}服務器
//設置socket參數
struct sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每一個字節用0填充
sockAddr.sin_family = AF_INET; //使用IPv4地址
sockAddr.sin_port = htons(80); //端口socket
//獲取主機名和地址信息
struct hostent *host; //host information
struct in_addr;// h_addr; //Internet address
if((host = gethostbyname(argv[1])) == NULL){
fprintf(stderr, "Failed on %s.\n", argv[1]);
exit(1);
}
sockAddr.sin_addr.s_addr = *((unsigned long *)host -> h_addr);
printf("Host IP: %s\n", inet_ntoa(sockAddr.sin_addr)); //打印主機IPorm
//鏈接到服務器
if(connect(sock, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) < 0){
fprintf(stderr, "Connect error.\n");
exit(1);
};get
/*===============================================================
* ***************與服務器通訊,收發數據************************
* =============================================================*/string
char request[512];//保存GET報頭
//request = "GET " + resource + " HTTP/1.1\r\nHost:" + host + "\r\nConnection:Close\r\n\r\n";
sprintf(request, "GET / HTTP/1.1\r\n");
strcat(request, "Host:");
strcat(request, argv[1]);
strcat(request, "\r\n");
strcat(request, "Accept: */*\r\n");
strcat(request, "User-Agent: Mozilla/4.0(compatible)\r\n");//假裝成瀏覽器
strcat(request, "Connection:Keep-Alive\r\n");
strcat(request, "\r\n\r\n");it
//發送數據
if(send(sock, request, strlen(request), 0) == -1){
fprintf(stderr, "Send request error.\n");
exit(1);
}io
//設置接收超時
struct timeval timeout = {1, 0}; //設置超時,左邊表明秒,右邊表明微秒,(1, 0)就是1秒0微秒
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(struct timeval));
//接收數據
int l = 0;
char buffer[512];
do{
l = recv(sock, buffer, sizeof(buffer) - 1, 0);
if(l < 0)
break;
*(buffer + l) = 0;
fputs(buffer, stdout);
}while(l > 0);form
//關閉套接字
close(sock);
return 0;
}file