Untitled
#include <sys/socket.h> #include <sys/types.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <arpa/inet.h> /* Parses JSON and extracts key from it returns 1 on success, 0 on json parse error or no key available */ extern int extractIntFromJSON(char json[], char key[], int* val); int main(int argc, char *argv[]) { int sockfd = 0, n = 0; int recvVal = 0; char recvBuff[1024]; struct sockaddr_in serv_addr; memset(recvBuff, 0 ,sizeof(recvBuff)); if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { return 1; } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0) { return 1; } if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { return 1; } while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0) { recvBuff[n] = 0; if(extractIntFromJSON(recvBuff, "example_key", &recvVal)) { printf("Received value: %d\n", recvVal); } else { printf("Invalid message received\n") } } if(n < 0) { printf("\n Read error \n"); } return 0; }
Leave a Comment