In modern computer science, network programming is an important field. The C language, as a low-level language, provides powerful capabilities for network communication. This article will introduce the basics of Socket programming in C, helping beginners understand how to use Sockets for simple network communication.
What is a Socket?
A Socket is a mechanism for inter-process communication that can transmit data between the same machine or different machines. In network programming, Sockets are typically used for data exchange between clients and servers.
Types of Sockets
- Stream Socket (SOCK_STREAM): Used for the TCP protocol, providing reliable, bidirectional, connection-based byte stream service.
- Datagram Socket (SOCK_DGRAM): Used for the UDP protocol, does not guarantee message delivery order or delivery, but is faster.
Basic Steps of Socket Programming
- Create a socket.
- Bind the socket to a local address and port.
- Listen for connection requests (server only).
- Accept connection requests (server only).
- Send and receive data.
- Close the socket.
Example Code
Below we will demonstrate how to create a TCP server and client through a simple example.
TCP Server Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
// Create socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Set socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
// Set address structure
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind socket to address
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Start listening for connection requests
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
printf("Waiting for client connection...\n");
// Accept client connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,(socklen_t*)&addrlen))<0) {
perror("accept");
exit(EXIT_FAILURE);
}
printf("Connected to client\n");
// Receive data and send response
read(new_socket , buffer , BUFFER_SIZE);
printf("Received: %s\n", buffer);
const char *response = "Hello from server";
send(new_socket , response , strlen(response), 0 );
close(new_socket);
close(server_fd);
return 0;
}
TCP Client Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#define PORT 8080
#define MESSAGE "Hello from client"
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
// Create socket file descriptor
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 address from text to binary form
if(inet_pton(AF_INET,"127.0.0.1",&serv_addr.sin_addr)<=0) {
printf("\nInvalid address/address not supported \n");
return -1;
}
// Try to connect to server
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\n");
char buffer[1024] = {0};
read(sock , buffer , sizeof(buffer));
printf("%s\n",buffer);
close(sock);
return 0;
}
How to Run the Example Code?
To run the above example, follow these steps:
- Create two files in the terminal:
<span>server.c</span>and<span>client.c</span>, and paste the server and client code respectively. - Compile both files:
gcc server.c -o server
gcc client.c -o client
- First, start the server:
./server
- Then, start the client in another terminal window:
./client
- You should see that both sides have successfully established a connection and can send messages to each other.
Conclusion
This article introduced the basics of Socket programming in C, including the basic steps and implementation of creating a TCP server and client. Through this simple example, you can understand how to use Sockets for basic data transmission. As you delve deeper into this topic, you can explore more advanced features such as multithreading, non-blocking I/O, etc. We hope this article helps you get started with C language network programming!