1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <arpa/inet.h>
- #define PORT 8081
- #define BUFFER_SIZE 1024
- int main() {
- int sock = 0;
- struct sockaddr_in serv_addr;
- char *message = "Hello Server\n";
- char buffer[BUFFER_SIZE] = {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);
- if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
- printf("\nInvalid address\n");
- return -1;
- }
- if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
- printf("\nConnection Failed \n");
- return -1;
- }
- send(sock, message, strlen(message), 0);
- printf("Message sent to server: %s", message);
- int read_size = read(sock, buffer, BUFFER_SIZE);
- if (read_size > 0) {
- printf("Received from server: %s", buffer);
- }
- close(sock);
- return 0;
- }
|