linux下用终端访问百度网站
百度的IP为:220.181.111.148,linux里编译下面代吗,
命令为:gcc -o http http.c
访问百度:./http 220.181.111.148 80
// http.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSIZE 10240
int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Parameter(s): <Server Address> <Server Port> <Echo Word>\n");
        exit(1);
    }
    char *servIP = argv[1];
    in_port_t servPort = atoi(argv[2]);
    char *echoString = "GET / HTTP/1.1\nHost: www.baidu\nUser-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6) Gecko/20050225 Firefox/1.0.1\nConnection: Keep-Alive\n\n";
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0) {
        printf("socket() failed\n");
        exit(1);
    }
    struct sockaddr_in servAddr;
    memset(&servAddr, 0, sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
    if (rtnVal == 0) {
        printf("inet_pton() failed, invalid address string\n");
        exit(1);
    }
    else if (rtnVal < 0) {
        printf("inet_pton() failed\n");
        exit(1);
    }
    servAddr.sin_port = htons(servPort);
    if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) {
        printf("connect() failed\n");
        exit(1);
    }
    size_t echoStringLen = strlen(echoString);
    ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
    if (numBytes < 0) {
        printf("send() failed");
        exit(1);
    }
    else if (numBytes != echoStringLen) {
        printf("send(), sent unexpected number of bytes");
        exit(1);
    }
    unsigned int totalBytesRcvd = 0;
    //printf("Received: ");   
linux终端下载软件
    while (totalBytesRcvd < echoStringLen) {
        char buffer[BUFSIZE];
        numBytes = recv(sock, buffer, BUFSIZE, 0);
        if (numBytes < 0) {
            printf("recv() failed");
            exit(1);
        }
        else if (numBytes == 0) {
            printf("recv(), connection closed prematurely");
            break;
        }
        totalBytesRcvd += numBytes;
        buffer[numBytes] = '\0'; 
        printf(buffer);
    }
    printf("\n");
    close(sock);
    exit(0);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。