int main(int argc, char *argv[]) { int sock; /* Socket */ struct sockaddr_in broadcastAddr; /* Broadcast Address */ /* Create a best-effort datagram socket using UDP */ if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror("socket failed"); exit(EXIT_FAILURE); } /* Construct bind structure */ memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */ broadcastAddr.sin_family = AF_INET; /* Internet address family */ broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ broadcastAddr.sin_port = htons(PORT); /* Broadcast port */ /* Bind to the broadcast port */ if (bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } char recvString[MAXRECVSTRING + 1]; int recvStringLen; int count = 0; while(1) { if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0) { perror("recvfrom failed"); exit(EXIT_FAILURE); } switch(recvString[0]) { case '1': printf("S1\n"); break; case '2': printf("S2\n"); break; case '3': printf("S3\n"); break; default: continue; } } close(sock); exit(0); }
时间: 2024-02-14 18:23:47 浏览: 144
这是一个使用UDP协议的C语言网络编程例子,通过创建一个socket和绑定一个广播地址,可以接收从其他主机发送的广播消息。在while循环中,通过recvfrom函数来接收消息,并通过switch语句来判断接收到的消息类型,并进行相应的处理。如果接收到的消息不是指定的类型,则继续等待接收下一条消息。最后,通过close函数关闭socket连接。
相关问题
C/C++ 编写一个服务器与客户端的群聊
以下是一个简单的基于TCP协议的服务器与客户端的群聊实现。该程序使用了多线程来支持多个客户端同时连接。
服务器代码(chat_server.c):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#define MAX_CLIENTS 10
#define BUFFER_SIZE 1024
int clients[MAX_CLIENTS];
int num_clients = 0;
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
void broadcast_message(char *message, int sender) {
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < num_clients; i++) {
if (clients[i] != sender) {
send(clients[i], message, strlen(message), 0);
}
}
pthread_mutex_unlock(&clients_mutex);
}
void *client_thread(void *arg) {
int client_fd = *(int*)arg;
char buffer[BUFFER_SIZE];
pthread_mutex_lock(&clients_mutex);
clients[num_clients++] = client_fd;
pthread_mutex_unlock(&clients_mutex);
while (1) {
int bytes_read = recv(client_fd, buffer, BUFFER_SIZE, 0);
if (bytes_read <= 0) {
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < num_clients; i++) {
if (clients[i] == client_fd) {
clients[i] = -1;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
close(client_fd);
return NULL;
}
buffer[bytes_read] = '\0';
broadcast_message(buffer, client_fd);
}
}
int main(int argc, char *argv[]) {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_len = sizeof(client_addr);
pthread_t tid;
if (argc != 2) {
printf("Usage: %s <port>\n", argv[0]);
exit(1);
}
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(atoi(argv[1]));
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("bind");
exit(1);
}
if (listen(server_fd, MAX_CLIENTS) < 0) {
perror("listen");
exit(1);
}
printf("Server listening on port %s...\n", argv[1]);
while (1) {
client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_len);
if (client_fd < 0) {
perror("accept");
exit(1);
}
pthread_create(&tid, NULL, client_thread, &client_fd);
}
return 0;
}
```
客户端代码(chat_client.c):
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int client_fd, port;
char buffer[BUFFER_SIZE];
struct hostent *server;
struct sockaddr_in server_addr;
if (argc != 3) {
printf("Usage: %s <hostname> <port>\n", argv[0]);
exit(1);
}
port = atoi(argv[2]);
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "Error: no such host\n");
exit(1);
}
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd < 0) {
perror("socket");
exit(1);
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
memcpy(&server_addr.sin_addr.s_addr, server->h_addr, server->h_length);
server_addr.sin_port = htons(port);
if (connect(client_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("connect");
exit(1);
}
printf("Connected to server %s:%d\n", argv[1], port);
while (1) {
printf("> ");
fgets(buffer, BUFFER_SIZE, stdin);
send(client_fd, buffer, strlen(buffer), 0);
}
return 0;
}
```
编译方法:
```
gcc -o chat_server chat_server.c -lpthread
gcc -o chat_client chat_client.c
```
运行方法:
```
./chat_server <port>
./chat_client <hostname> <port>
```
其中,`<port>`是服务器监听的端口号,`<hostname>`是服务器的主机名或IP地址。客户端连接服务器后,可以输入任意文本并发送到服务器,服务器会将该文本广播给所有连接的客户端。
利用setsocketopt()使用嵌套字支持广播,并编写两个程序,其中一个发送广播数据,另一个接收广播数据。
好的,我会根据你的要求回答你的问题。以下是利用setsocketopt()使用嵌套字支持广播的步骤:
1. 创建一个 UDP 套接字
```
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
```
2. 设置套接字选项,使其支持广播
```
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
```
3. 绑定 IP 地址和端口号
```
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT); // PORT 为自定义的端口号
addr.sin_addr.s_addr = htonl(INADDR_ANY); // 使用 INADDR_ANY 表示可以接收来自任意 IP 地址的广播数据
bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
```
4. 发送广播数据
```
char buffer[MAXBUF];
memset(buffer, 0, MAXBUF);
strcpy(buffer, "Hello, world!"); // 自定义广播数据
struct sockaddr_in broadcast_addr;
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_port = htons(PORT); // 广播的目标端口号
broadcast_addr.sin_addr.s_addr = inet_addr("255.255.255.255"); // 广播的目标 IP 地址
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&broadcast_addr, sizeof(broadcast_addr));
```
5. 接收广播数据
```
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[MAXBUF];
memset(buffer, 0, MAXBUF);
int n = recvfrom(sockfd, buffer, MAXBUF, 0, (struct sockaddr *)&client_addr, &client_addr_len);
// 处理接收到的广播数据
printf("Received broadcast message: %s\n", buffer);
```
下面是两个程序的代码,一个发送广播数据,另一个接收广播数据:
发送广播数据的程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 12345
#define MAXBUF 1024
int main(int argc, char *argv[]) {
// 创建 UDP 套接字
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
// 设置套接字选项,使其支持广播
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
// 绑定 IP 地址和端口号
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
// 发送广播数据
char buffer[MAXBUF];
memset(buffer, 0, MAXBUF);
strcpy(buffer, "Hello, world!");
struct sockaddr_in broadcast_addr;
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_port = htons(PORT);
broadcast_addr.sin_addr.s_addr = inet_addr("255.255.255.255");
sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&broadcast_addr, sizeof(broadcast_addr));
printf("Sent broadcast message: %s\n", buffer);
close(sockfd);
return 0;
}
```
接收广播数据的程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 12345
#define MAXBUF 1024
int main(int argc, char *argv[]) {
// 创建 UDP 套接字
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("socket");
exit(1);
}
// 设置套接字选项,使其支持广播
int broadcast = 1;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
// 绑定 IP 地址和端口号
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
exit(1);
}
// 接收广播数据
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
char buffer[MAXBUF];
memset(buffer, 0, MAXBUF);
int n = recvfrom(sockfd, buffer, MAXBUF, 0, (struct sockaddr *)&client_addr, &client_addr_len);
// 处理接收到的广播数据
printf("Received broadcast message: %s\n", buffer);
close(sockfd);
return 0;
}
```
阅读全文