c语言 编写一个套接字程序,要求服务器等待客户的连接请求,一旦有客户连接,服务器打印出客户端的IP地址和端口,并向客户端发送欢迎信息。
时间: 2024-02-27 17:51:56 浏览: 107
以下是一个简单的 C 代码示例,实现了上述功能:
服务端代码(server.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888 // 端口号
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
socklen_t client_address_length = sizeof(client_address);
char buffer[1024] = {0};
// 创建一个 TCP 套接字
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 配置服务器地址和端口号
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = INADDR_ANY;
server_address.sin_port = htons(PORT);
// 绑定到指定的端口
if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 开始监听连接请求
if (listen(server_socket, 1) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
printf("等待客户连接...\n");
// 等待客户连接
if ((client_socket = accept(server_socket, (struct sockaddr *)&client_address, &client_address_length)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
printf("客户端 %s:%d 连接成功!\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
// 向客户端发送欢迎信息
strcpy(buffer, "欢迎连接到服务器!");
if (send(client_socket, buffer, strlen(buffer), 0) < 0) {
perror("send failed");
exit(EXIT_FAILURE);
}
// 关闭客户端连接
close(client_socket);
return 0;
}
```
客户端代码(client.c):
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888 // 端口号
#define SERVER_ADDRESS "127.0.0.1" // 服务器地址
int main() {
int client_socket;
struct sockaddr_in server_address;
char buffer[1024] = {0};
// 创建一个 TCP 套接字
if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 配置服务器地址和端口号
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr(SERVER_ADDRESS);
server_address.sin_port = htons(PORT);
// 连接到服务端
if (connect(client_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// 接收服务端发送的欢迎信息
if (recv(client_socket, buffer, 1024, 0) < 0) {
perror("recv failed");
exit(EXIT_FAILURE);
}
printf("%s\n", buffer);
// 关闭连接
close(client_socket);
return 0;
}
```
运行服务端代码后,会打印出 "等待客户连接...",表示服务器正在等待客户端连接。然后运行客户端代码,客户端连接到服务器并接收到欢迎信息。服务端会打印出客户端的 IP 地址和端口号。
阅读全文