TCP/IP socket programming in C(一)

// client.c
#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

#include <sys/socket.h>
#include <netinet/in.h> /* inet_addr */


int main(int argc, char *argv[])
{
        int socket_desc;
        struct sockaddr_in server;
        char *message, server_reply[2000];

        // Create socket
        socket_desc = socket(AF_INET, SOCK_STREAM, 0);
        if (socket_desc == -1) {
                printf("Could not create socket\n");
        }

        server.sin_addr.s_addr = inet_addr("74.125.235.20");
        server.sin_family = AF_INET;
        server.sin_port = htons(80);

        // Connect to remote server
        if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) {
                puts("connect error\n");
                return 1;
        }

        puts("Connected\n");

        // Send some data
        message = "GET / HTTP/1.1\r\n\r\n";
        if (send(socket_desc, message, strlen(message), 0) < 0) {
                puts("Send failed\n");
                return 1;
        }
        puts("Data Send\n");

        // Receive a reply from the server
        if (recv(socket_desc, server_reply, 2000, 0) < 0) {
                puts("recv failed");
        }
        puts("Reply received\n");
        puts(server_reply);

        // Close socket
        close(socket_desc);
        
	return 0;
}


参考:http://www.binarytides.com/socket-programming-c-linux-tutorial/

你可能感兴趣的:(TCP/IP socket programming in C(一))