Page 1 of 1
How to bind a socket to specific net_if
Posted: Sun Sep 15, 2024 9:19 am
by wxd2024
Greetings,
I am using both ethernet and wifi in the current project. Does setting the default net_if to one of the two before each time socket connect is called force the socket to be bound with the specific net_if? Assume the target ip address is in an ip section of neither net_ifs and and ip_v4 routing picks the default net_if.
Bests
Wang
Re: How to bind a socket to specific net_if
Posted: Thu Sep 19, 2024 4:16 am
by nopnop2002
I haven't tried it, but I think you just need to specify the IP address of the interface you want to bind to.
Code: Select all
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in localaddr = {0};
localaddr.sin_family = AF_INET;
// for WiFi
localaddr.sin_addr.s_addr = inet_addr("192.168.10.103");
// for Ethernet
//localaddr.sin_addr.s_addr = inet_addr("192.168.10.104");
bind(s, (sockaddr*)&localaddr, sizeof(localaddr));
Re: How to bind a socket to specific net_if
Posted: Fri Sep 20, 2024 5:13 pm
by wxd2024
nopnop2002 wrote: ↑Thu Sep 19, 2024 4:16 am
I haven't tried it, but I think you just need to specify the IP address of the interface you want to bind to.
Code: Select all
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in localaddr = {0};
localaddr.sin_family = AF_INET;
// for WiFi
localaddr.sin_addr.s_addr = inet_addr("192.168.10.103");
// for Ethernet
//localaddr.sin_addr.s_addr = inet_addr("192.168.10.104");
bind(s, (sockaddr*)&localaddr, sizeof(localaddr));
Thanks a lot for the reply. Not quite familiar with lwip stuff, is bind() only used for a server socket to listen to connection requests on specific netif or can it also be used for a client socket to select a specific netif for reaching the target server? In my case, I am attempting to force a client socket to use specific netif for reaching the server. Appreciative for any further hints.
Re: How to bind a socket to specific net_if
Posted: Tue Sep 24, 2024 5:24 am
by nopnop2002
bind is used for a server socket to listen to connection requests.
If you want to force client sockets to use a specific netif to reach the server, this sample is just the right fit.
https://github.com/espressif/esp-idf/tr ... _multi_net
Re: How to bind a socket to specific net_if
Posted: Wed Sep 25, 2024 1:56 pm
by MicroController
The example shows different ways to do it. One is in fact to
bind() the (client) socket to an interface's IP address before connecting.
Re: How to bind a socket to specific net_if
Posted: Sat Sep 28, 2024 4:50 pm
by wxd2024
The example is clearly the right way to go. Really appreciate the help form both of you!