socket connect() & bind() together?

deleyd used Ask the Experts™
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:

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
Watch Question

Do more with

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

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


How about if i put the commands in the correct order. Then what would happen?
Software Engineer
Distinguished Expert 2018
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.bind(, ...)     # assuming one of YOUR interfaces is
socka.listen()    - now you are ready to accept connection...
sockc = socka.accept()   to actual receive a connection....

in another program / trhead:
nociSoftware Engineer
Distinguished Expert 2018

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

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