Statistics
| Branch: | Revision:

grapes / som / Tests / net_helpers.c @ 8ab58ec7

History | View | Annotate | Download (1.02 KB)

1
/*
2
 *  Copyright (c) 2010 Luca Abeni
3
 *  Copyright (c) 2010 Csaba Kiraly
4
 *
5
 *  This is free software; see lgpl-2.1.txt
6
 */
7

    
8
#include <sys/ioctl.h>
9
#include <sys/socket.h>
10
#include <netinet/in.h>
11
#include <arpa/inet.h>
12
#include <net/if.h>     /* For struct ifreq */
13
#include <unistd.h>
14
#include <stdlib.h>
15
#include <stdio.h>
16
#include <string.h>
17

    
18
#include "net_helpers.h"
19

    
20
const char *iface_addr(const char *iface)
21
{
22
    int s, res;
23
    struct ifreq iface_request;
24
    struct sockaddr_in *sin;
25
    char buff[512];
26

    
27
    s = socket(AF_INET, SOCK_DGRAM, 0);
28
    if (s < 0) {
29
        return NULL;
30
    }
31

    
32
    memset(&iface_request, 0, sizeof(struct ifreq));
33
    sin = (struct sockaddr_in *)&iface_request.ifr_addr;
34
    strcpy(iface_request.ifr_name, iface);
35
    /* sin->sin_family = AF_INET); */
36
    res = ioctl(s, SIOCGIFADDR, &iface_request);
37
    if (res < 0) {
38
        perror("ioctl(SIOCGIFADDR)");
39
        close(s);
40

    
41
        return NULL;
42
    }
43
    close(s);
44

    
45
    inet_ntop(AF_INET, &sin->sin_addr, buff, sizeof(buff));
46

    
47
    return strdup(buff);
48
}
49

    
50

    
51