gpt4 book ai didi

c++ - 无法在matlab中的UDP客户端和linux中的服务器之间发送数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:06 29 4
gpt4 key购买 nike

我在一台机器的 matlab 中有 UDP 程序,在另一台机器的 cpp 中有 UDP 程序。通过将 cpp 代码作为客户端运行并将 matlab 代码作为服务器运行,我能够将数据从 cpp 代码发送到 matlab 。当我尝试将 matlab 作为客户端运行,将 cpp 作为服务器运行时,我无法将数据发送到 cpp。在上述两种情况下,程序都在两台不同的机器上运行。我尝试在同一台机器上将 matlab 作为客户端,将 cpp 作为服务器,然后它就可以工作了.

我的cpp代码

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "port.h"

#define BUFSIZE 2048

int
main(int argc, char **argv)
{
struct sockaddr_in myaddr; /* our address */
struct sockaddr_in remaddr; /* remote address */
socklen_t addrlen = sizeof(remaddr); /* length of addresses */
int recvlen; /* # bytes received */
int fd; /* our socket */
unsigned char buf[BUFSIZE]; /* receive buffer */


/* create a UDP socket */

if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket\n");
return 0;
}

/* bind the socket to any valid IP address and a specific port */

memset((char *)&myaddr, 0, sizeof(myaddr));
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
myaddr.sin_port = htons(SERVICE_PORT);

if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
perror("bind failed");
return 0;
}

/* now loop, receiving data and printing what we received */
for (;;) {
printf("waiting on port %d\n", SERVICE_PORT);
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
printf("received %d bytes\n", recvlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%s\"\n", buf);
}
}
/* never exits */
}

最佳答案

在此处发布评论中的答案以提高可见度:

由于这些程序在同一台计算机上运行时可以运行,但在不同的计算机上运行时则不行,这表明存在防火墙问题(这意味着计算机正在阻止入站流量)。在 Linux 中,可以根据以下说明暂时禁用 iptables(这就是防火墙的名称):https://www.cyberciti.biz/faq/turn-on-turn-off-firewall-in-linux/

如果这解决了问题,请不要忘记重新打开 iptables。然后只需在 iptables 中为您的程序添加一个异常(exception),类似于这些说明:https://help.ubuntu.com/community/IptablesHowTo#Allowing_Incoming_Traffic_on_Specific_Ports

关于c++ - 无法在matlab中的UDP客户端和linux中的服务器之间发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41670692/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com