Modelica socket communication (Part 1: socket library, code listing)
This page lists the code referred to in my blog post here).
Socket.c contains the following (note that this hasn’t been tested under Windows).
#ifdef _WIN32
#include "winsock2.h"
#else
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#endif
#include <stdio.h>
static int s = 0;
static char receive_buffer[255];
int startup()
{
#ifdef _WIN32
WSADATA wsa;
return WSAStartup(MAKEWORD(2,0), &wsa);
#else
return 0;
#endif
}
int create_socket(const char* ip_address, int port)
{
#ifdef _WIN32
struct SOCKADDR_IN addr;
#else
struct sockaddr_in addr;
#endif
s = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(ip_address);
#ifdef _WIN32
if (connect(s, (struct SOCKADDR*)&addr, sizeof(addr)) == INVALID_SOCKET)
return 1;
else
return 0;
#else
if (connect(s, (struct sockaddr*)&addr, sizeof(addr)) < 0)
return 1;
else
return 0;
#endif
}
void send_message(char* buf)
{
send(s, buf, strlen(buf), 0);
}
char* receive_message()
{
recv(s, receive_buffer, 255, 0);
return receive_buffer;
}
int cleanup()
{
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}