sending Broadcasts

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Howdy,

I try to send a broadcast UDP packet from a linux C program.
I can send to every address where I want, but not to the broadcast address.
What's wrong? Here is the source, I hope somebody can help a newbie in linux
network C programing :)

#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>

main(int argc, char ** argv)
{
 int   socketfd;
 struct sockaddr_in clientAddress;
 struct sockaddr_in serverAddress;
 struct hostent  *host;
 unsigned int  sendPort;
 int   sendSize;
 int   structSize;

 if (argc != 4) {
  fprintf(stderr, "Usage: %s hostname port data\n", argv[0]);
  exit(0);
 }

 if ((sendPort = atoi(argv[2])) < 0) {
  fprintf(stderr, "Bad port\n");
  exit(1);
 }


 /* find host */
 host = gethostbyname(argv[1]);
 if (host == NULL) {
  fprintf(stderr, "Unknown host %s\n", argv[1]);
  exit(1);
 }


 /* fill in the structure serverAddress with the address of server */
 serverAddress.sin_family = AF_INET;
 memcpy(&serverAddress.sin_addr, host->h_addr, host->h_length);
 serverAddress.sin_port = htons(sendPort);

 /* open a UDP socket (an Internet datagram socket) */
 if ((socketfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
  fprintf(stderr, "Can't open datagram socket\n");
  exit(1);
 }

 /* bind any local address for us. */
 clientAddress.sin_family = AF_INET;
 clientAddress.sin_addr.s_addr = htonl(INADDR_ANY);
 clientAddress.sin_port = htons(0);

 if(bind(socketfd,
  (struct sockaddr*)&clientAddress,
  sizeof(clientAddress)) < 0) {
  fprintf(stderr, "Can't bind local address\n");
  close(socketfd);
  exit(1);
 }

 /* send a datagram */
 sendSize   = strlen(argv[3]);
 structSize = sizeof(serverAddress);

 if (sendto(socketfd, argv[3], sendSize, 0,
     (struct sockaddr *)&serverAddress, structSize) != sendSize) {
  fprintf(stderr, "sento error\n");
  close(socketfd);
  exit(1);
 }

 printf("%d bytes sent (%s)\n", sendSize, argv[3]);
 close(socketfd);
 exit(0);
}


-
: send the line "unsubscribe linux-net" in
the body of a message to majordomo@vger.rutgers.edu


[Index of Archives]     [Netdev]     [Ethernet Bridging]     [Linux 802.1Q VLAN]     [Linux Wireless]     [Kernel Newbies]     [Security]     [Linux for Hams]     [Netfilter]     [Git]     [Bugtraq]     [Yosemite News and Information]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux PCI]     [Linux Admin]     [Samba]

  Powered by Linux