Matlab C-based Mex file with sockets not running

182 views Asked by At

I'd like to learn a bit more about networking tools in C/C++ and I decided to copy some C echo server coded into a mex file to play with it through Matlab. The problem is that when I build the mex file and execute it, it seems to run forever without listening on a socket or anything. I included some print statements in the code to test if we're entering the mex file at all, but at present none of them print at all. Here's the code:

#define char16_t UINT16_T //shenanigans with the compiler

#include "mex.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

void echo(){

    char str[100];
    int listen_fd, comm_fd;
    struct sockaddr_in servaddr;

    listen_fd = socket(AF_INET, SOCK_STREAM,0);
    bzero(&servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htons(INADDR_ANY);
    servaddr.sin_port = htons(22000);

    bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    mexPrintf("Listening");

    listen(listen_fd, 10);

    comm_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);
    mexPrintf("Connected");

    while(1)
    {
        bzero(str, 100);
        read(comm_fd, str, 100);
        mexPrintf("Echoing back - %s", str);
        write(comm_fd, str, strlen(str)+1);
    }

}

void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    mexPrintf("Starting");

    echo();

    mexPrintf("Finishing");
}

Any help would be greatly appreciated.

1

There are 1 answers

0
Matt On BEST ANSWER

So after testing the echo server, it actually seems to be working, it just doesn't print so long as there is a socket open. Quite strange!