C语言中的套接字编程是进行网络通信的基础。在华为云国际站代理商充值的场景下,了解套接字编程可以帮助你实现自动化的网络请求和数据传输。下面是一个简单的C语言套接字编程示例,用于在客户端和服务器之间进行通信。
首先,编写服务器端代码:
#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 addrlen = sizeof(address);
char buffer[BUFFER_SIZE] = {0};
const char *hello = "Hello from server";
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定套接字到端口
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
close(server_fd);
exit(EXIT_FAILURE);
}
// 读取客户端发送的数据
read(new_socket, buffer, BUFFER_SIZE);
printf("Message from client: %sn", buffer);
// 发送数据给客户端
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sentn");
// 关闭套接字
close(new_socket);
close(server_fd);
return 0;
}
然后,编写客户端代码:
#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 sock = 0;
struct sockaddr_in serv_addr;
char buffer[BUFFER_SIZE] = {0};
const char *hello = "Hello from client";
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Socket creation error");
exit(EXIT_FAILURE);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将IP地址转换为二进制形式
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
perror("Invalid address/ Address not supported");
exit(EXIT_FAILURE);
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("Connection failed");
exit(EXIT_FAILURE);
}
// 发送数据给服务器
send(sock, hello, strlen(hello), 0);
printf("Hello message sentn");
// 读取服务器发送的数据
read(sock, buffer, BUFFER_SIZE);
printf("Message from server: %sn", buffer);
// 关闭套接字
close(sock);
return 0;
}
在这个示例中,服务器和客户端通过TCP连接进行简单的字符串消息交换。这些代码可以帮助你理解C语言套接字编程的基本概念,并为你在华为云国际站代理商充值中实现相关功能提供基础。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/190865.html