/* * client.c - demo program that connects to server running on SERVER_ADDRESS and PORT * sends message to server, receives message from server * this program has only minor edits to the original at https://www.geeksforgeeks.org/socket-programming-cc/ * works with server.c * first start the server running, then on a separate computer start the client running * * usage: ./client * compile: gcc -o client client.c * * * author: Geeks for Geeks Tim Pierson, Fall 2022, minor edits * CS 50, Fall 2022 */ #include #include #include #include #include #include #include #include //get ip address from command line with: //ip addr // or //wget -O - -q https://checkip.amazonaws.com const char *SERVER_ADDRESS = "129.170.64.104"; const int PORT = 8080; int connect_to_server(const char *server_addr) { int sock = 0, client_fd; struct sockaddr_in serv_addr; char* hello = "Hello from client"; char buffer[1024] = { 0 }; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if (inet_pton(AF_INET, server_addr, &serv_addr.sin_addr) <= 0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if ((client_fd = connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) < 0) { printf("\nConnection Failed \n"); return -1; } printf("Got connection\n"); printf("Sending message %s\n",hello); send(sock, hello, strlen(hello), 0); printf("Hello message sent\n"); printf("Waiting for reply\n"); read(sock, buffer, 1024); printf("Server reply: %s\n", buffer); // closing the connected socket close(client_fd); return 0; } int main() { int ret = connect_to_server(SERVER_ADDRESS); if ( ret == 0) { printf("Had GOOD connection\n"); } else { printf("Had BAD connection\n"); } }