123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #define SERVER_ADDR "127.0.0.1"
- #define PORT 8083
- #define BUFFER_SIZE 1024
- int main()
- {
- int client_socket;
- struct sockaddr_in server_addr={0};
- char buffer[BUFFER_SIZE];
- // Create socket
- if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
- {
- perror("Socket creation failed");
- exit(EXIT_FAILURE);
- }
- // Define server address
- server_addr.sin_family = AF_INET;
- server_addr.sin_port = htons(PORT);
- server_addr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
- // Convert IP address to binary form
- //if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0)
- //{
- // perror("Invalid address");
- //exit(EXIT_FAILURE);
- //}
- // Connect to the server
- if (connect(client_socket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
- {
- perror("Connection failed");
- close(client_socket);
- exit(EXIT_FAILURE);
- }
- printf("Connected to server\n");
- //for(int i=0;i<6;i++)
- // {
- // Send a message to the server
- const char *message = "testing!";
- send(client_socket, message, strlen(message), 0);
- printf("Message sent to server: %s\n",message );
- //}
- //Receive server's response
- int n = recv(client_socket, buffer, BUFFER_SIZE, 0);
- if (n < 0)
- {
- perror("Receive failed");
- close(client_socket);
- exit(EXIT_FAILURE);
- }
- buffer[n] = '\0'; // Null-terminate the received string
- printf("Received from server: %s\n", buffer);
- // Close the socket
- close(client_socket);
- return 0;
- }
|