Link to home
Start Free TrialLog in
Avatar of JeepGuy
JeepGuy

asked on

How do I specify/bind a socket to a specific NIC?

I'm trying to configure multiple sockets in one app and have them bound to specific addresses & NICs.  I have one TCP socket setup on one address, but I need to set up a separate UDP socket for broadcasting to use a completely different address configured on the other NIC.  I can't seem to specify the UDP socket to send FROM the second NIC.  I've done the....

send_struct.sin_family = AF_INET;
send_struct.sin_addr.s_addr = inet_addr("164.217.14.10");
bind(my_udp_socket, (SOCKADDR*) &send_struct, sizeof(send_struct));

...where NIC 1 is 192.168.1.10 and NIC 2 is 164.217.14.10 (mask: 255.255.0.0)

But, that doesn't seem to do it.  When I call my sendto() function.....

send_struct.sin_port = htons("3000");
send_struct.sin_addr.s_addr = ("164.217.255.255");
sendto(my_udp_socket, (int8 *)pkt, len, 0, (const struct sockaddr *)&send_struct, sizeof(send_struct));

...I don't see it show up on the wire (and the return value from sendto() returns the number of bytes I'm sending and I'm connected to an actual hub, not a switch...thus Wireshark shows everything).  I've searched for an example on someone setting up multiple socket connections bound to different NICs/subnets and haven't found a solution that works yet.  Any ideas?
Avatar of vanillasprinkles
vanillasprinkles

you will probably be better off setting up two sin_addr's and the corresponding ports and binds for each address:port you want to have in your program (yes you can use send_struct for each unique ip:port you want but it can get messy and hard to keep track of)

I dont think it matters much, but in code i've written, my sendto does not use (const struct sockaddr *), but rather, (struct sockaddr *)
Avatar of JeepGuy

ASKER

I have already set up two different sockaddr_in structs for the different sockets.  I even tried using one for the bind and another for the sendto() func for the same socket.
sounds awful

oh, i did notice (forgot to add it to my first comment)

sin_addr.s_addr = inet_addr("IP")

your second sin_addr.s_addr=  does not have the inet_addr - not sure if you wanted it like that or not.


I have referenced this page (http://www.linuxhowtos.org/C_C++/socket.htm) many times in the past; what I would to is start a test project for yourself, with binding to two unique IP:Port's and exporting that working code to your project, so that you dont overwhelm yourself in your full sized project.
ASKER CERTIFIED SOLUTION
Avatar of JeepGuy
JeepGuy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial