Skip to content

Instantly share code, notes, and snippets.

@neilalexander
Created June 29, 2012 19:07
Show Gist options
  • Save neilalexander/3020008 to your computer and use it in GitHub Desktop.
Save neilalexander/3020008 to your computer and use it in GitHub Desktop.
Some interesting code that will send a UDP packet to all available broadcast/point-to-point IPv4 addresses
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
int main(int argc, const char** argv)
{
int on = 1;
char* sendstring = "HELLO";
int sendlen = 6;
struct ifaddrs *ifap;
if (getifaddrs(&ifap) == 0)
{
struct ifaddrs* intf = ifap;
struct sockaddr_in intfaddr, sendaddr;
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd < 0)
{
perror("socket");
return -1;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char*) &on, sizeof(on)) < 0)
{
perror("setsockopt -> SO_BROADCAST");
return -1;
}
while (intf)
{
memset(&intfaddr, 0, sizeof(struct sockaddr_in));
memset(&sendaddr, 0, sizeof(struct sockaddr_in));
intfaddr.sin_family = AF_INET;
intfaddr.sin_port = htons(3456);
if (intf->ifa_addr != NULL && ((struct sockaddr_in*) intf->ifa_addr)->sin_family == AF_INET)
intfaddr.sin_addr = ((struct sockaddr_in*) intf->ifa_addr)->sin_addr;
sendaddr.sin_family = AF_INET;
sendaddr.sin_port = htons(3456);
if (intf->ifa_flags & IFF_BROADCAST)
{
if (intf->ifa_broadaddr != NULL && ((struct sockaddr_in*) intf->ifa_broadaddr)->sin_family == AF_INET)
sendaddr.sin_addr = ((struct sockaddr_in*) intf->ifa_broadaddr)->sin_addr;
}
else
if (intf->ifa_flags & IFF_POINTOPOINT)
{
if (intf->ifa_dstaddr != NULL && ((struct sockaddr_in*) intf->ifa_dstaddr)->sin_family == AF_INET)
sendaddr.sin_addr = ((struct sockaddr_in*) intf->ifa_dstaddr)->sin_addr;
}
if (sendaddr.sin_addr.s_addr != 0)
{
printf("interface %s\n", intf->ifa_name);
char sendipaddr[32], intfipaddr[32];
inet_ntop(AF_INET, &sendaddr.sin_addr, sendipaddr, 32);
inet_ntop(AF_INET, &intfaddr.sin_addr, intfipaddr, 32);
printf("\t%s -> %s\n", intfipaddr, sendipaddr);
if (sockfd > 0)
{
int sent = sendto(sockfd, &sendstring, strlen(sendstring), 0, (struct sockaddr*) &sendaddr, sizeof(sendaddr));
if (sent < 0)
perror("sendto");
}
}
intf = intf->ifa_next;
}
freeifaddrs(ifap);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment