socket connect() & bind() together?

deleyd
deleyd used Ask the Experts™
on
My understanding is for sockets, connect sets the destination IP address, and bind sets the return IP address.

What would happen if I created two sockets, socka and sockb, and did:
socka.connect(10.1.1.2);
socka.bind(99.0.0.1);
sockb.connect(99.0.0.1);

Open in new window

If I now send some data to sockb, will the data go to socka and then will socka forward that data to IP address 10.1.1.2?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
nociSoftware Engineer
Distinguished Expert 2018

Commented:
A bind needs to PRECEED connect.

socka = socket(....)
socka.bind(srcaddress...)     (set source to use, needs to be one of the local interface assigned IP addresses)
socka.connect(dstaddress.....)   uses socka bound source address to connect to destination.....

So NO that will not work as you intended.

if you need to forward data YOU need to program that yourself....
read from sockb and then write to sock a & vice versa.

You can check the sources of netcat / socat for network copy functiones.
deleydSoftware Engineer

Author

Commented:
How about if i put the commands in the correct order. Then what would happen?
Software Engineer
Distinguished Expert 2018
Commented:
no the network layer will not forward packets from one socket to another.....
what would happen??? most probably some error codes being produced or at worst: nothing but some open sockets doing nothing.

a socket is a connecton between your program and a "network session"  1:1....
another socket is another network session....

What you can do:

socka.socket()
socka.bind(192.168.1.10, ...)     # assuming one of YOUR interfaces is 192.168.1.10
socka.listen()    - now you are ready to accept connection...
sockc = socka.accept()   to actual receive a connection....
sockc.receive.....


in another program / trhead:
sockb.socket()
sockb.connect(192.168.1.10...)
sockb.write.....
nociSoftware Engineer
Distinguished Expert 2018

Commented:
If you want to see what is passing through: use wireshark + appropriate filters. (for commandline use: tshark / tcpdump).
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Maybe describe exactly what you're trying to accomplish, listing all processes you'll be using + exact data flow required.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial