Using sockets correctly in unix
Hi rodney Here,i am new to unix programming and had little doubt about on unix "C" sockets Hopefully this is a good place to ask this question. I was looking for some advice on how best to use unix c sockets. I'm writing a simple http client, so currently I create a socket with the socket() method, and then call connect() to connect to the server (I'm using a TCP stream, rather than UDP). What I want to know is should I create a new socket using socket(), every time I want to connect to a new server, or can I just close the connection, and call connect() to connect to a new server?
For example.Currently I create the socket, and connect to www.google.com. then I make a standard HTTP Get request for index.htm.This returns a 302 (Resource moved to www.google.co.uk. Now to connect to www.google.co.uk, currently I'm closing my socket,then I use socket() to create a new one, and finally call connect() to connectwww.google.co.uk. Is it possible to just close() the socket, and then call connect() passing the credentials for www.google.co.uk ? I tried this, but it seemed to fail to connect.Originally I assumed that I should always pair a connect() with close(), but perhaps I should pair socket() with close() ?
Re: Using sockets correctly in unix
No, because 'close' makes the file descriptor invalid since the socket is now gone. There is nothing to 'connect'.When you are finished with a socket and no longer need it, 'close' it. If you fully 'shutdown' the connection, the socket you are left with cannot be used for anything. All you can do is 'close' it.
hope it helps you.
Re: Using sockets correctly in unix
Thanks, that the clarification that I was looking for. :biggrin: