karan421
karan421

Reputation: 863

Get ip-address of local NIC from kernel module

I am writing a kernel module which forms its own packet at ip level and then sends the data . I just want to know how to find the ip address of a local network interface.

Upvotes: 1

Views: 3691

Answers (3)

radzee
radzee

Reputation: 1

We have if_getconfig function available in linux-x.y.z/Documentation/networking/ifenslave.c file which is a very good example of how to use ioctls and fetch address from kernel space

Upvotes: 0

jørgensen
jørgensen

Reputation: 10579

Wanting to read interface addresses reeks of a design problem. However, if you are looking for determining the preferred source address to use when contacting a remote peer is given in struct rt6_info.rt6i_prefsrc after obtaining it with ip6_route_output. Something along the lines of (with no implied guarantees):

int pick_addr(struct in6_addr *saddr, struct net *net, const struct in6_addr *daddr)
{
    struct rt6_info *rt;
    struct flowi6 fl6;
    int ret;
    memset(&fl6, 0, sizeof(fl6));
    memcpy(&fl6.daddr, daddr, sizeof(*daddr));
    dst = (struct rt6_info *)ip6_route_output(net, NULL /* or sk if you have it */, &fl6);
    ret = rt->dst.error;
    if (ret == 0)
            memcpy(saddr, &rt->rt6i_prefsrc.addr, sizeof(*saddr));

    dst_release(&rt->dst);
    return ret;
}

Upvotes: 1

werewindle
werewindle

Reputation: 3029

There are defined ioctls SIOCGIFADDR (to get if address) and SIOCSIFADDR (to set if address).

All device configuration for IPv4 is done in net/ipv4/devinet.c. You can refer to this source file to get more information.

Upvotes: 1

Related Questions