Windows Socket Programming in C

后端 未结 3 1506
后悔当初
后悔当初 2020-12-16 06:06

I am taking a networking class where the Professor is literally reading the book to the class. Needless to say I have no Idea what I am doing. Our semester project is to cop

3条回答
  •  隐瞒了意图╮
    2020-12-16 06:35

    The following is a simple socket program (simple http client) that will run on both Windows and Linux. If you are using "gcc on windows" then you need to compile using the following command:

    gcc prog_name.c -lws2_32
    

    Code:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    #if defined(_WIN32) || defined(_WIN64)
        #include 
    #else
        #include 
        #include 
    #endif
    
    #define MSG_SIZE 1024
    #define REPLY_SIZE 65536
    
    int main(int argc, char *argv[])
    {
        int s = -1;
        struct sockaddr_in server;
        char message[MSG_SIZE] = {0}, server_reply[REPLY_SIZE] = {0};
        int recv_size = 0;
    
    #if defined(_WIN32) || defined(_WIN64)    
        WSADATA wsa;
        if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) {
            printf("\nError: Windows socket subsytsem could not be initialized. Error Code: %d. Exiting..\n", WSAGetLastError());
            exit(1);
        }
    #endif
        
        //Create a socket
        if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)    {
            printf("Error: Could not create socket: %s. Exiting..\n", strerror(errno));
            exit(1);
        }
    
        // Fill in server's address
        memset(&server, 0, sizeof(server));
        server.sin_addr.s_addr = inet_addr("172.217.160.238"); // google.com
        server.sin_family = AF_INET;
        server.sin_port = htons(80);
    
        // Connect to server
        if (connect(s, (struct sockaddr *)(&server), sizeof(server)) < 0) {
            printf("Error: Could not connect to server: %s. Exiting..\n", strerror(errno));
            exit(1);
        }
        
        // Send HTTP request
        strcpy(message, "GET / HTTP/1.1\r\n\r\n");
        if(send(s, message, strlen(message), 0) < 0) {
            printf("Error: Could not send http request to server: %s. Exiting..\n", strerror(errno));
            exit(1);
        }
        
        // Receive a reply from the server
        printf("\nWaiting for server reply..\n");
        if((recv_size = recv(s, server_reply, REPLY_SIZE, 0)) < 0) {
            printf("Error: Something wrong happened while getting reply from server: %s. Exiting..\n", strerror(errno));
            exit(1);
        }
    
        server_reply[REPLY_SIZE - 1] = 0;
    
        printf("\nServer Reply:\n\n");
        printf("%s\n", server_reply);
    
        // Close the socket
    #if defined(_WIN32) || defined(_WIN64)  
        closesocket(s);
        WSACleanup();
    #else
        close(s);
    #endif
    
        exit(0);
    } // end of main
    

提交回复
热议问题