-
Binding
hi guys i am trying to bind a name to a socket,
here is the bind chunk :
Code:
/* Bind the socket */
if (bind(sockfd, (struct sockaddr *)&my_addr,
sizeof(struct sockaddr)) == -1) {
perror("bind");
exit(1);
}
I get this error:
Code:
bind: Bad file descriptor
I do not know what the source of the problem could be.
sockfd is decaled like so:
Code:
/* listen on sock_fd, new connection on new_fd*/
int sockfd, new_fd;
thank you in advance
-
You need to call socket() and set sockfd equal to the return value of the socket() function before you can bind() it.
-
wow that was fast,
thanx again!
itsme
-
Another question,
i am using a wrapper function to do the socket(),
Code:
int Socket(int family, int type, int protocol)
{
int n;
if ( (n = socket(family, type, protocol)) < 0) {
perror("socket error");
exit(1);
}
return(n);
}
in the main body i do this:
Code:
/* Establish Socket */
sockfd = Socket(AF_INET, SOCK_STREAM, 0);
bind gives me error:
Code:
bind: Address already in use
is it because i have 'n' in the function body set to the socket and then i try to set it to something else: 'sockfd' ?
thank you in advance
-
Try using setsockopt() to set the option SO_REUSEADDR after calling socket() and before calling bind():
Code:
{
int opt = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));
}
-
thanks again itsme,
one more thing,
my server is supposed to send http requests,
do u know how that works?
my idea is that i have a tcp connection with the host and i just write "GET /index.html HTTP/1.0" as a string
does a regular browser do the same as well?
and to check if a file exists i will use the return value of fopen ( is there a better way? )
thank you so much
-
Hmm, I'm confused here. You're bind()ing a socket which is generally only done when you want to be the server. If that's the case then the remote side, the side that connects to your server, would be the one sending the HTTP request. Then your server would handle the request and send the page.
If you just want to connect to port 80 of a webserver with your program then you don't need bind(). You only need to use socket() and connect().
Here's the URL for the HTTP RFC: http://www.faqs.org/rfcs/rfc2616.html