0

I wrote a simple UDP broadcast sample. When I write the IP address to the struct sockaddr_in with inet_addr("192.168.152.128"), I cannot receive the message from another UDP broadcast program with the broadcast 192.168.152.255. But when I write htonl(INADDR_ANY), it can receive the message. Why could that be?

This the code:

#include"myhead.h"
char rbuf[50];
char wbuf[50];
int main()
{
  int udp, size, len, opt = 1;
  struct sockaddr_in laddr;
  struct sockaddr_in raddr;

  laddr.sin_family = AF_INET;
  laddr.sin_port = htons(8888);
  laddr.sin_addr.s_addr = htonl(INADDR_ANY);

  //when i write inet_addr("192.168.152.128")
  //it cannot receive the message.

  size = sizeof(struct sockaddr_in);
  udp = socket(AF_INET, SOCK_DGRAM, 0);
  setsockopt(udp, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof opt);
  bind(udp, (struct sockaddr*)&laddr, size);

  len = sizeof(struct sockaddr);
  while (1)
  {
    recvfrom(udp, rbuf, 50, 0, (struct sockaddr*)&raddr, &len);
    printf("%s\n", rbuf);
    bzero(rbuf, 50);
  }
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183
ZJE
  • 9
  • 1

0 Answers0