Home > Blockchain >  Strange behaviour while sending broadcast message
Strange behaviour while sending broadcast message

Time:12-14

I have two programs: client and server. They're trying to find themselves in local network using broadcast.

Client sends simple packet on broadcast with SERVER_PORT (known before) and server prints info about connection, but when i tried this solution I found some strange behavaiour, when I uncomment last two lines of server.c server prints (one custom struct)

Connection from: 0.0.0.0 on port: 0

after commenting those lines everything works properly, am I missing something?

server.c

  int broadcast_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  struct sockaddr_in broadcast_addr;
  broadcast_addr.sin_addr.s_addr = INADDR_ANY;
  broadcast_addr.sin_port = htons(SERVER_PORT);
  broadcast_addr.sin_family = AF_INET;

  if (bind(broadcast_socket, (struct sockaddr *)&broadcast_addr,
           sizeof(broadcast_addr))) {
    perror("bind");
  }

  struct sockaddr_in recv_addr;
  char buf[MAX_PACKET_SIZE];
  socklen_t len;

  if (recvfrom(broadcast_socket, buf, MAX_PACKET_SIZE, 0,
               (struct sockaddr *)&recv_addr, &len) < 0) {
    perror("recvfrom");
  }

  printf("Connection from: %s on port: %d\nMessage: %s\n",
         inet_ntoa(recv_addr.sin_addr), ntohs(recv_addr.sin_port), buf);

  /* struct network_packet packet; */

  /* struct sockaddr_in my_addr; */

client.c

int find_server(struct sockaddr_in *out) {
  struct sockaddr_in broadcast;
  struct network_packet packet;
  int yes = 1;
  socklen_t len;

  broadcast.sin_addr.s_addr = INADDR_ANY;
  broadcast.sin_port = htons(CLIENT_PORT);
  broadcast.sin_family = AF_INET;


  int socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

  if (bind(socket_fd, (struct sockaddr *)&broadcast, sizeof(broadcast))) {
    perror("bind");
  }

  if (get_broadcast_addr(&broadcast.sin_addr)) {
    return -1;
  }

  printf("Target address: %s\n", inet_ntoa(broadcast.sin_addr));

  broadcast.sin_port = htons(SERVER_PORT);
  broadcast.sin_family = AF_INET;

  setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));

  char buf[10] = "test";

  sendto(socket_fd, buf, strlen(buf), 0, (struct sockaddr *)&broadcast,
         sizeof(broadcast));

  if (recvfrom(socket_fd, &packet, sizeof(packet), 0,
               (struct sockaddr *)&broadcast, &len) < 0) {
    perror("recvfrom");
  }

  struct sockaddr_in *sa = (struct sockaddr_in *)packet.data;

  memcpy(out, sa, packet.header.packet_length);

  return 0;
}
struct network_packet_header {
  enum network_packet_type type;
  int packet_length;
};

struct network_packet {
  struct network_packet_header header;
  unsigned char data[MAX_DATA_LENGTH];
};

CodePudding user response:

You have to initialize the variable you pass as recvfrom's addrlen to the size of the address struct.

  • Related