在Linux中,Socket 5实际上是一个基于TCP/IP协议族的socket编程接口
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 12345
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd, addr_len;
struct sockaddr_in server_addr, client_addr;
char buffer[BUFFER_SIZE];
// 创建socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 配置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(PORT);
// 绑定socket
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
addr_len = sizeof(client_addr);
// 接受客户端连接
if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t *)&addr_len)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取并输出客户端发送的数据
read(client_fd, buffer, BUFFER_SIZE);
printf("Message from client: %s\n", buffer);
// 向客户端发送数据
send(client_fd, "Hello from server!", strlen("Hello from server!"), 0);
printf("Message sent to client\n");
// 关闭socket
close(client_fd);
close(server_fd);
return 0;
}
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#define PORT 12345
#define SERVER_IP "127.0.0.1"
#define BUFFER_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE] = {0};
// 创建socket
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 配置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
// 连接到服务器
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("connect");
exit(EXIT_FAILURE);
}
// 向服务器发送数据
send(client_fd, "Hello from client!", strlen("Hello from client!"), 0);
printf("Message sent to server\n");
// 读取并输出服务器发送的数据
read(client_fd, buffer, BUFFER_SIZE);
printf("Message from server: %s\n", buffer);
// 关闭socket
close(client_fd);
return 0;
}
编译并运行这两个程序,首先启动服务器,然后启动客户端。服务器将接收到客户端发送的消息,并向客户端发送回复。客户端收到服务器的回复后,结束通信。