c - IOT Client-server communication using JSON object -
i have written code client server communication using iot... using json object parsing... api json_object_object_foreach(jobj,key,val) not getting executed, giving segmentation fault. please find out solution , let me know.
server.c
#include <unistd.h> #include <string.h> #include <json/json.h> #include<stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <stdlib.h> #include<netinet/ip.h> #include<arpa/inet.h> #include<errno.h> #include<sys/ioctl.h> #include<fcntl.h> #define magic 'k' #define my_cmd1 _iowr(magic,1,int *) struct stepper { int rot; int dir; int angle; }step; char buf[1024]; int x,y,z,i=0; int a[3]; void json_parse(json_object *jobj,int *a) { enum json_type type; printf("type: ",type); printf("json parsed\n"); json_object_object_foreach(jobj,key,val) { type = json_object_get_type(val); switch (type) { printf("json parsed 1\n"); case json_type_int: printf("json_type_intn\n"); printf("the value %d\n", a[i++]=json_object_get_int(val)); break; } } } int main(int argc,char *argv[]) { int sockfd,accptfd,len; int fd,cmd,d,q; char buf[1024]; struct sockaddr_in server,client; server.sin_family=af_inet; server.sin_port=htons(atoi(argv[1])); server.sin_addr.s_addr = inaddr_any; sockfd=socket(af_inet,sock_stream,0); if(sockfd<0) printf("the fd %d\n",sockfd); printf("before bind\n"); bind(sockfd,(struct sockaddr *)&server,sizeof(server)); perror("bind"); listen(sockfd,5); len=sizeof(client); printf("the server up\n"); accptfd=accept(sockfd,(struct sockaddr *)&client,&len); send(accptfd,"hello server",14,0); recv(accptfd,buf,14,0); printf("rec data %s\n",buf); fd=open("stepp",o_rdwr); printf("enter stepper motor specification\n"); q=recv(accptfd,buf,1024,0); puts(buf); json_object * jobj = json_tokener_parse(buf); printf("the json obj %s\n",json_object_to_json_string(jobj)); json_parse(jobj,a); ioctl(fd,my_cmd1,&step); close(fd); close(accptfd); close(sockfd); return 0; }
client.c
#include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/ip.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<json/json.h> #include<stdlib.h> char *str="{\"a\":1,\"b\":2,\"c\":360}"; int main(int argc, char *argv[]) { int sock_s,sock_c,s_len; char buf[20]; char buf1[20]="hello server"; struct sockaddr_in server; server.sin_family = af_inet; server.sin_addr.s_addr = inet_addr(argv[1]); server.sin_port = htons(atoi(argv[2])); s_len = sizeof(server); sock_s = socket(af_inet,sock_stream,0); printf("the str %s\n",str); if(connect(sock_s,(struct sockaddr *)&server,s_len)<0) { perror("connect:"); } recv(sock_s,buf,20,0); printf("the read dat %s\n",buf); printf("enter data send\n"); scanf("%s",buf); send(sock_s,buf,20,0); send(sock_s,str,1024,0); close(sock_s); return 0; }
Comments
Post a Comment