基于c++ 实现一个udp server程序,监听广播IP地址为255.255.255.255 端口为13400的client发送的请求消息,解析client的ip地址,并给clientf发送应答
时间: 2024-02-06 20:09:00 浏览: 160
监听程序运行的程序 C++
5星 · 资源好评率100%
以下是一个基于C++实现的UDP服务器程序,可以监听广播IP地址为255.255.255.255,端口为13400的客户端发送的请求消息,解析客户端的IP地址,并给客户端发送应答。
```
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main()
{
// 创建UDP套接字
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
{
cerr << "socket() failed!" << endl;
return -1;
}
// 允许广播
int broadcast = 1;
if(setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) == -1)
{
cerr << "setsockopt() failed!" << endl;
close(sockfd);
return -1;
}
// 绑定本地IP和端口
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(13400);
if(bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
{
cerr << "bind() failed!" << endl;
close(sockfd);
return -1;
}
// 接收客户端请求
char recv_buf[1024];
struct sockaddr_in client_addr;
socklen_t len = sizeof(client_addr);
while(true)
{
memset(recv_buf, 0, sizeof(recv_buf));
int n = recvfrom(sockfd, recv_buf, sizeof(recv_buf), 0, (struct sockaddr*)&client_addr, &len);
if(n == -1)
{
cerr << "recvfrom() failed!" << endl;
continue;
}
// 解析客户端IP地址
char client_ip[INET_ADDRSTRLEN];
memset(client_ip, 0, sizeof(client_ip));
if(inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip)) == NULL)
{
cerr << "inet_ntop() failed!" << endl;
continue;
}
cout << "Received request from " << client_ip << endl;
// 发送应答
const char* send_buf = "Hello, client!";
n = sendto(sockfd, send_buf, strlen(send_buf), 0, (struct sockaddr*)&client_addr, len);
if(n == -1)
{
cerr << "sendto() failed!" << endl;
continue;
}
}
// 关闭套接字
close(sockfd);
return 0;
}
```
这个程序使用了socket、setsockopt、bind、recvfrom、inet_ntop和sendto等函数实现了UDP服务器的基本功能。在运行时,该程序会不断接收客户端发送的请求消息,并解析客户端的IP地址,最后给客户端发送应答消息。
阅读全文