c - Getting IP address from struct sockaddr doesn't work for 32bit compilation -
i have small client/server app sends/receives udp discovery packets. when udp packet received want display source ip. client/server code based on udp example beej: http://beej.us/guide/bgnet/output/html/multipage/clientserver.html
when compile 64bit ip displayed expected when compile 32bit (-m32 option) doesn't right value @ all.
code snippit:
// sockaddr, ipv4 or ipv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == af_inet) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } ... printf("listener: waiting recvfrom...\n"); addr_len = sizeof their_addr; if ((numbytes = recvfrom(sockfd, buf, maxbuflen-1 , 0, (struct sockaddr *)their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("listener: got packet %s\n", inet_ntop(their_addr->sa_family, get_in_addr((struct sockaddr *)their_addr), s, sizeof s)); printf("sockaddr: "); (i=0; i<sizeof(struct sockaddr_in); i++) printf("%x ", ((char *)their_addr)[i]); printf("\n");
correct output when compiled 64bit:
listener: waiting recvfrom... listener: got packet 192.168.20.6 sockaddr: 2 0 ffffff80 19 ffffffc0 ffffffa8 14 6 64 2e 40 0 0 0 0 0
wrong output when compiled -m32:
listener: waiting recvfrom... listener: got packet 168.32.140.255 sockaddr: 2 0 ffffff80 19 ffffffa8 20 ffffff8c ffffffff 50 ffffffdd 7d fffffff7 4 0 0 0
i don't understand why there problem using get_in_addr or inet_ntop when compiling 32bit?
addr_len
should set size of address structure, not size of pointer (it's happening work in 64 bit mode, because pointers twice large in mode). should be:
addr_len = sizeof *their_addr;
incidentally, how their_addr
initialised? there has real structure point to.
Comments
Post a Comment