Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c - bind socket to network interface

How can I bind a socket to a particular network interface? I tried using setsockopt on server side, but the clients can still access the service through both eth0 and lo interfaces.

I can achieve this by setting the particular IP address using serv_addr.sin_addr.s_addr.

But I suspect that we can bind to an interface using only setsockopt (without mentioning the IP address).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can bind to a specific interface by setting SO_BINDTODEVICE socket option.

struct ifreq ifr;

memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0");
if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
    ... error handling ...
}

Warning: You have to be root and have the CAP_NET_RAW capability in order to use this option.

The second method is that you can resolv IP address tied to an interface with getifaddrs().

Follow the latter link for a comprehensive example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...