i trying send single unsigned char
through buffer. using buffer of size 2
unsigned char temp_buf [2]; temp_buf [0]= (unsigned char) 0xff; temp_buf [1]= null;
and sendto
functions looks this:
if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0) perror("sendto");
it compiles no issues, @ run time error:
sendto: invalid argument
which means there wrong buffer im using. suspected issue might because im using siezeof changed strlen(temp_buf) still no luck!
edit: trying make question simpler not including whole code here is, sorry that!
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> #include "port.h" #define bufsize 2048 int main(int argc, char **argv) { struct sockaddr_in myaddr; /* our address */ struct sockaddr_in remaddr; /* remote address */ socklen_t addrlen = sizeof(remaddr); /* length of addresses */ int recvlen; /* # bytes received */ int fd; /* our socket */ int msgcnt = 0; /* count # of messages received */ unsigned char buf[bufsize]; /* receive buffer */ /* create udp socket */ if ((fd = socket(af_inet, sock_dgram, 0)) < 0) { perror("cannot create socket\n"); return 0; } /* bind socket valid ip address , specific port */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = af_inet; myaddr.sin_addr.s_addr = htonl(inaddr_any); myaddr.sin_port = htons(service_port); if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); return 0; } /* loop, receiving data , printing received */ printf("waiting on port %d\n", service_port); //recvfrom(fd, buf, bufsize, 0, (struct sockaddr *)&remaddr, &addrlen); //buf [0] = 0xff; unsigned char temp_buf [2]; temp_buf [0]= (unsigned char) 0xff; temp_buf [1]= '\0'; if (sendto(fd, temp_buf, sizeof (temp_buf), 0, (struct sockaddr *)&remaddr, addrlen) < 0) perror("sendto"); else printf("%s \n", "communication established"); }
the contents of remaddr
uninitialized. in other words, you're not telling sendto
send data.
you need populate struct ip , port wish send to.
if uncomment call recvfrom
, subsequently packet other service, remaddr
gets populated ip/port sent packet, can use send packet back. without that, need fill in remaddr
.
Comments
Post a Comment