Linux C: How to know the default interface for int

2019-05-25 21:00发布

I want to find out the default network in use. My current method was to find all IP addresses and compare it to the default gateway IP address, but that sounds silly. What is the correct way of doing it ?

UPDATE

I want to use a C program, not by commands ...

1条回答
2楼-- · 2019-05-25 21:53

You can try a slightly dirtier but infinitely easier approach:

cnicutar@lemon:~$ ip route show to 0.0.0.0/0
default via X.Y.Z.T dev eth0  proto static
                        ^^^^

So you can try:

FILE *cmd = popen("ip route show", "r");
fgets(str, LEN, cmd);

Then you can use strtok, strstr etc.

查看更多
登录 后发表回答