linux udp 两个socket绑254.254.254.253端口28005和192.168.131.1端口15003分别发送和接受消息
时间: 2024-01-21 21:19:11 浏览: 148
基于网络的udp通讯发送端和接收端.zip_socket
以下是一个简单的示例代码,其中包括绑定和发送接收消息的过程:
```c++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUF_LEN 1024
int main()
{
int send_sock, recv_sock;
struct sockaddr_in send_addr, recv_addr;
char send_buf[BUF_LEN], recv_buf[BUF_LEN];
int send_len, recv_len;
// 创建发送socket
if ((send_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket create failed");
exit(EXIT_FAILURE);
}
// 设置发送地址
memset(&send_addr, 0, sizeof(send_addr));
send_addr.sin_family = AF_INET;
send_addr.sin_addr.s_addr = inet_addr("254.254.254.253");
send_addr.sin_port = htons(28005);
// 创建接收socket
if ((recv_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("socket create failed");
exit(EXIT_FAILURE);
}
// 设置接收地址
memset(&recv_addr, 0, sizeof(recv_addr));
recv_addr.sin_family = AF_INET;
recv_addr.sin_addr.s_addr = inet_addr("192.168.131.1");
recv_addr.sin_port = htons(15003);
// 绑定接收socket
if (bind(recv_sock, (struct sockaddr*)&recv_addr, sizeof(recv_addr)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
// 发送消息
strcpy(send_buf, "Hello, this is a test message.");
send_len = strlen(send_buf);
if (sendto(send_sock, send_buf, send_len, 0, (struct sockaddr*)&send_addr, sizeof(send_addr)) < 0)
{
perror("sendto failed");
exit(EXIT_FAILURE);
}
// 接收消息
memset(recv_buf, 0, BUF_LEN);
if ((recv_len = recvfrom(recv_sock, recv_buf, BUF_LEN, 0, NULL, NULL)) < 0)
{
perror("recvfrom failed");
exit(EXIT_FAILURE);
}
printf("Received message: %s\n", recv_buf);
close(send_sock);
close(recv_sock);
return 0;
}
```
其中,首先创建了发送和接收的socket,然后分别设置了发送和接收的地址和端口。接着,绑定了接收socket并发送了一条消息。最后通过recvfrom函数接收了来自另一端的消息,并将其打印出来。
请注意,这里使用了inet_addr函数将IP地址转换为网络字节序的整数形式,因为socket API中使用的都是网络字节序。如果您不确定如何转换,请参考相关资料。
阅读全文