probonopd / announce

Announce services on the network with Zeroconf/Bonjour with minimal overhead.
15 stars 5 forks source link

Automatically find out local IP address and hostname #1

Closed probonopd closed 9 years ago

probonopd commented 9 years ago

Find local IP address and hostname and use it automatically. Something along the lines below. Who wants to help me integrate this into announce.c?

// To find out our own IP address
#include <sys/socket.h>
#include <ifaddrs.h>

int done = 0;

void term(int signum)
{
    printf("\nReceived SIGTERM, exiting...\n");

    done = 1;
}

const char *ownip() {
    // http://www.binarytides.com/get-local-ip-c-linux/

    FILE *f;
    char line[100] , *p , *c;

    f = fopen("/proc/net/route" , "r");

    while(fgets(line , 100 , f))
    {
        p = strtok(line , " \t");
        c = strtok(NULL , " \t");

        if(p!=NULL && c!=NULL)
        {
            if(strcmp(c , "00000000") == 0)
            {
                // printf("Default interface is: %s\n" , p);
                break;
            }
        }
    }

    //which family do we require , AF_INET or AF_INET6
    int fm = AF_INET;
    struct ifaddrs *ifaddr, *ifa;
    int family , s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    //Walk through linked list, maintaining head pointer so we can free list later
    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
        {
            continue;
        }

        family = ifa->ifa_addr->sa_family;

        if(strcmp( ifa->ifa_name , p) == 0)
        {
            if (family == fm)
            {
                s = getnameinfo( ifa->ifa_addr, (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6) , host , NI_MAXHOST , NULL , 0 , NI_NUMERICHOST);

                if (s != 0)
                {
                    printf("getnameinfo() failed: %s\n", gai_strerror(s));
                    exit(EXIT_FAILURE);
                }
            }
        }
    }

    freeifaddrs(ifaddr);
    return(host);
}

const char *ownhostname() {
    char hostname[1024];
    hostname[1023] = '\0';
    gethostname(hostname, 1023);
    char str2[16];
    strcpy(str2, ".local");
    strcat(hostname, str2);
    return(hostname);
}