How to bind a socket to specific net_if

wxd2024
Posts: 7
Joined: Wed Jun 19, 2024 7:48 am

How to bind a socket to specific net_if

Postby wxd2024 » Sun Sep 15, 2024 9:19 am

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

nopnop2002
Posts: 51
Joined: Thu Oct 03, 2019 10:52 pm

Re: How to bind a socket to specific net_if

Postby nopnop2002 » 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));

Who is online

Users browsing this forum: Basalt, Bing [Bot] and 314 guests