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
How to bind a socket to specific net_if
-
- Posts: 109
- Joined: Thu Oct 03, 2019 10:52 pm
- Contact:
Re: How to bind a socket to specific net_if
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
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.nopnop2002 wrote: ↑Thu Sep 19, 2024 4:16 amI 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));
-
- Posts: 109
- Joined: Thu Oct 03, 2019 10:52 pm
- Contact:
Re: How to bind a socket to specific net_if
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
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
-
- Posts: 1692
- Joined: Mon Oct 17, 2022 7:38 pm
- Location: Europe, Germany
Re: How to bind a socket to specific net_if
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
The example is clearly the right way to go. Really appreciate the help form both of you!