编写一个套接字程序,要求服务器等待客户的连接请求,一旦有客户连接,服务器打印出客户端的IP地址和端口,并向客户端发送欢迎信息。使用getpeername函数
时间: 2024-02-09 16:12:46 浏览: 52
好的,以下是一个简单的套接字程序,实现了上述要求:
服务端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define PORT 8080
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置地址重用
int opt = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
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");
exit(EXIT_FAILURE);
}
// 监听连接请求
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 等待连接请求
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 打印客户端IP地址和端口
char client_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &address.sin_addr, client_ip, INET_ADDRSTRLEN);
printf("Client connected: %s:%d\n", client_ip, ntohs(address.sin_port));
// 向客户端发送欢迎信息
char *welcome_message = "Welcome to the server!";
send(new_socket, welcome_message, strlen(welcome_message), 0);
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define PORT 8080
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
char *hello_message = "Hello from client!";
// 创建套接字
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
// 设置服务器地址和端口
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// 将点分十进制的IP地址转换为网络字节序的32位二进制数
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0) {
printf("\nInvalid address/ Address not supported \n");
return -1;
}
// 连接服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
printf("\nConnection Failed \n");
return -1;
}
// 接收服务器发送的欢迎信息
char buffer[1024] = {0};
int valread = read(sock, buffer, 1024);
printf("%s\n", buffer);
// 发送消息到服务器
send(sock, hello_message, strlen(hello_message), 0);
printf("Hello message sent\n");
return 0;
}
```
运行服务端程序后,可以看到等待客户端连接请求:
```
$ ./server
Client connected: 127.0.0.1:41448
```
运行客户端程序后,可以看到客户端连接到服务器并接收到欢迎信息:
```
$ ./client
Welcome to the server!
Hello message sent
```
阅读全文