Skip to content

Instantly share code, notes, and snippets.

@loderunner
Last active April 2, 2017 03:13
Show Gist options
  • Save loderunner/ec7d4725daca39283606 to your computer and use it in GitHub Desktop.
Save loderunner/ec7d4725daca39283606 to your computer and use it in GitHub Desktop.
get broadcast address for an interface
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <net/if.h>
#include <netdb.h>
static void show_interface_broadaddr(int fd, const char *name) {
int family;
struct ifreq ifreq;
char host[128];
memset(&ifreq, 0, sizeof ifreq);
strncpy(ifreq.ifr_name, name, IFNAMSIZ);
if(ioctl(fd, SIOCGIFBRDADDR, &ifreq) != 0)
{
fprintf(stderr, "Could not find interface named %s", name);
return; /* ignore */
}
getnameinfo(&ifreq.ifr_broadaddr, sizeof(ifreq.ifr_broadaddr), host, sizeof(host), 0, 0, NI_NUMERICHOST);
printf("%-24s%s\n", name, host);
}
static void list_interfaces(int fd) {
struct ifreq *ifreq;
struct ifconf ifconf;
char buf[16384];
unsigned i;
size_t len;
ifconf.ifc_len = sizeof(buf);
ifconf.ifc_buf = buf;
if (ioctl(fd, SIOCGIFCONF, &ifconf) != 0)
{
perror("ioctl(SIOCGIFCONF)");
exit(EXIT_FAILURE);
}
printf("Listing all interfaces:\n");
ifreq = ifconf.ifc_req;
i = 0;
while (i < ifconf.ifc_len)
{
#ifndef linux
len = IFNAMSIZ + ifreq->ifr_addr.sa_len;
#else
len = sizeof(struct ifreq);
#endif
printf("%s\n", ifreq->ifr_name);
ifreq = (struct ifreq*)((char*)ifreq + len);
i += len;
}
}
int main(int argc, char** argv) {
int sock;
struct ifreq ifreq;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
perror("socket()");
exit(EXIT_FAILURE);
}
if (argc == 1)
{
list_interfaces(sock);
}
else if (argc == 2)
{
show_interface_broadaddr(sock, argv[1]);
}
close(sock);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment