C Programming: Sending Data with send() Function 🎯

beginner
10 min

C Programming: Sending Data with send() Function 🎯

Welcome back to CodeYourCraft! Today, we're going to dive into one of the essential functions in C programming - send(). This function is crucial for sending data over a network socket. Let's get started! 📝

Understanding the send() Function 💡

The send() function is used to send data over a socket. It is part of the socket library in C and is defined as follows:

c
int send(int sockfd, const void *buf, size_t len, int flags);

Let's break down the parameters:

  • sockfd: This is the file descriptor of the socket over which data needs to be sent.
  • buf: A pointer to the data to be sent.
  • len: The number of bytes to be sent from the buffer.
  • flags: Flags that modify the behavior of the send() function.

Sending Data with send() 💡

Let's see a practical example of using the send() function to send a simple message:

c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> int main() { int sockfd; struct sockaddr_in serv_addr; char *message = "Hello, World!"; ssize_t sent; // Create socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket creation error"); exit(EXIT_FAILURE); } // Configure the server's address serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(9000); inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr); // Connect to the server if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { perror("connection error"); exit(EXIT_FAILURE); } // Send the message sent = send(sockfd, message, strlen(message), 0); if (sent < 0) { perror("send error"); exit(EXIT_FAILURE); } printf("Sent message: %s\n", message); close(sockfd); return 0; }

In this example, we create a simple C program that connects to a server, and sends a message using the send() function.

Quiz 📝

In the next lesson, we will explore more about receiving data with the recv() function. Stay tuned! 🎯