a b/SimpleSocketExample/main.c
1
#include <stdlib.h>
2
#include <stdio.h>
3
#include <errno.h>
4
5
#include <unistd.h>
6
#include <fcntl.h>
7
#include <sys/stat.h>
8
#include <arpa/inet.h>
9
#include <sys/types.h>
10
#include <sys/socket.h>
11
#include <netinet/in.h>
12
#include <stdint.h>
13
#include <string.h>
14
#include <math.h>
15
16
 void printUsage();
17
18
 typedef int bool;
19
 #define true 1
20
 #define false 0
21
22
int main( int argc, const char* argv[] )
23
{
24
/* ********************************************
25
 * Actual socket code
26
 **********************************************/
27
28
int socketfd; // socket handle
29
30
// open the socket
31
// http://man7.org/linux/man-pages/man2/socket.2.html
32
socketfd = socket(AF_INET, // IPv4
33
                  SOCK_STREAM, // a TCP connection
34
                  6); // protocol. 6 is TCP
35
36
if (!socketfd)
37
{
38
  printf("opening socket failed\n");
39
  return 1;
40
}
41
42
// no need to bind this one. CODESYS is already bound so it is acting as a server.
43
// We are a client, so we don't need a fixed address/port to be reached at
44
45
// connect to CODESYS
46
47
// first we need to create the struct where we put the connection info
48
struct sockaddr_in saCodesys;
49
// init the struct
50
bzero((char *) &saCodesys, sizeof(saCodesys));
51
// put in the information
52
saCodesys.sin_family = AF_INET; // IPv4
53
saCodesys.sin_port = htons(1200); // CODESYS port
54
55
// Convert IPv4 address from text to binary form
56
  if(inet_pton(AF_INET, "127.0.0.1", (struct sockaddr *)&saCodesys.sin_addr)<=0)
57
  {
58
      printf("Invalid address/ Address not supported \n");
59
      // close the socket
60
      close(socketfd);
61
      return 2;
62
  }
63
64
  if (connect(socketfd, (const struct sockaddr *)&saCodesys, sizeof(saCodesys)) < 0)
65
  {
66
    printf("Connection Failed %d\n", errno);
67
    // close the socket
68
    close(socketfd);
69
    return 3;
70
  }
71
72
/* *************************************
73
 * Sending data
74
 ***************************************/
75
    // super smart A.I. algorithm putting out production targets once a second
76
    uint16_t uiProductionTarget = 0;
77
    int counter = 0;
78
79
    while (1)
80
    {
81
      uiProductionTarget = (sin(counter / 100.0) + 1) * 100;
82
83
      if (send(socketfd, &uiProductionTarget, sizeof(uiProductionTarget), 0 /* no flags */) < 0)
84
      {
85
        printf("send failed. Ending.\n");
86
        break;
87
      }
88
      else
89
      {
90
        printf("sent target: %d\n", uiProductionTarget);
91
      }
92
93
      sleep(1); // wait a ms before doing the math again.
94
      counter ++;
95
    }
96
97
98
    // close the socket
99
    close(socketfd);
100
    printf("closing down.\n", );
101
102
    return 0;
103
}
104
105
void printUsage()
106
{
107
  printf("just run it\n");
108
}