TCP Client in C

Shared by: devcanvas

c

1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <unistd.h>
5
#include <arpa/inet.h>
6

7
#define SERVER_PORT 8080
8
#define BUFFER_SIZE 1024
9

10
int main() {
11
    int sock;
12
    struct sockaddr_in server_address;
13
    char buffer[BUFFER_SIZE];
14
    char *message = "Hello, Server!";
15

16
    // Create socket
17
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
18
        perror("Socket creation failed");
19
        exit(EXIT_FAILURE);
20
    }
21

22
    // Define server address
23
    server_address.sin_family = AF_INET;
24
    server_address.sin_port = htons(SERVER_PORT);
25

26
    // Convert IPv4 address from text to binary
27
    if (inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr) <= 0) {
28
        perror("Invalid address/ Address not supported");
29
        close(sock);
30
        exit(EXIT_FAILURE);
31
    }
32

33
    // Connect to the server
34
    if (connect(sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
35
        perror("Connection failed");
36
        close(sock);
37
        exit(EXIT_FAILURE);
38
    }
39

40
    // Send message to server
41
    send(sock, message, strlen(message), 0);
42
    printf("Message sent: %s\n", message);
43

44
    // Receive server response
45
    int bytes_received = recv(sock, buffer, BUFFER_SIZE, 0);
46
    if (bytes_received > 0) {
47
        buffer[bytes_received] = '\0';
48
        printf("Message received: %s\n", buffer);
49
    }
50

51
    // Close socket
52
    close(sock);
53

54
    return 0;
55
}

How It Works

  1. Socket Creation:

    • The socket function initializes a socket using IPv4 (AF_INET) and TCP (SOCK_STREAM).
  2. Server Address Setup:

    • The server’s IP address and port are defined in a sockaddr_in structure.
  3. Connection:

    • The connect function establishes a connection to the specified server address.
  4. Communication:

    • The send function transmits data to the server.
    • The recv function waits for a response from the server.
  5. Cleanup:

    • The close function releases the socket resources.

Example Usage

  • Server: Set up a simple TCP server on port 8080 (e.g., using Python or another tool).
  • Client: Compile and run this program to connect to the server, send a message, and print the server’s response.
Love it? Share it!

DevCanvas DevCanvas Logo

Online Editor with a collection of awesome frontend code and code snippets for developers of all levels.

Legal & Support

Stand with Palestine 🇵🇸! DO NOT BE SILENCED

© 2025 DevCanvas. All rights reserved.