sockets - Connecting to a device in LAN over TCP/IP using C -
i'm trying connect device(allen-bradley plc) residing in lan using c. device i'm trying connect not host application listens application (since have no control on it). once connection established, can send , receive packets requesting data. developed working application in c# (using system.net.sockets) connects , communicates device. however, c code i'm writing seems fail @ part establishes connection. here's source code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef windows #include <winsock2.h> #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #endif #include <errno.h> int main() { char *servip = "192.168.10.31"; in_port_t servport = 503; int sock = socket(af_inet, sock_stream, ipproto_tcp); if (sock < 0) { fprintf(stderr, "socket() failed: %s\n", strerror(errno)); exit(1); } struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = af_inet; int rtnval = inet_pton(af_inet, servip, &servaddr.sin_addr.s_addr); if (rtnval <= 0) { printf("failed"); exit(1); } if (connect(sock, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { printf("failed connecting"); exit(1); } else { printf("connected"); } char x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; printf("tere"); write(sock, x, sizeof(x)); char buffer[1024]; recv(sock, buffer, 1024, 0); printf("data received: %s", buffer); }
you forgot set port call connect()
.
you defined servport
variable, not assigning servaddr
variable.
so should add:
servaddr.sin_port = htons(servport);
or simply:
servaddr.sin_port = htons(503);
Comments
Post a Comment