SP_
SP_

Reputation: 391

Not able to send data between UDP client in matlab and server in linux

I have UDP program in matlab in one machine and UDP in cpp in other machine. I am able to send data from cpp code to matlab , by running cpp code as client and matlab code as server. When I tried running matlab as client and cpp as server I am not able to send the data to cpp.In Both the above cases programms are running in two different machines.I tried matlab as client and cpp as server in same machine then its worked.

my cpp code

#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 */
}

Upvotes: 1

Views: 650

Answers (1)

Tim Sweet
Tim Sweet

Reputation: 645

Posting the answer from the comments here for visibility:

Since the programs work when run on the same computer, but not when run on separate computers, that points to a firewall issue (meaning the computer is blocking inbound traffic). In Linux, iptables (that's what the firewall is called) can be temporarily disabled per the instructions at: https://www.cyberciti.biz/faq/turn-on-turn-off-firewall-in-linux/

If that solves the problem, don't forget to turn iptables back on. Then just add an exception in iptables for your program similar to these instructions: https://help.ubuntu.com/community/IptablesHowTo#Allowing_Incoming_Traffic_on_Specific_Ports

Upvotes: 1

Related Questions