I'm currently learning C programming, especially sockets...so don't flame me or anything for the lack of error handling below. Could somebody tell me why this code gives me error 99 when using the bind() function. Error 99 is: Cannot assign requested address. Thanks in advance, can't wait for this to work so i can get further.
Code: Select all
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
int main(int argc, char *argv[])
{ //creates integers for use
int sockid, clilen, newsockid,n,z;
char buffer[256];
//creates sockaddr_in structures for server and client addresses, ports etc.
struct sockaddr_in serv_addr, cli_addr;
bzero((char *) &serv_addr, sizeof(serv_addr));
/*Creates new socket, AF_INET specifies IPv4, SOCK_STREAM specifies
the type of communication other choice is SOCK_DGRAM. The 0 tells the system to
choose the best protocol depending on the communication type chosen, this can also
be set to something like IPPROTO_TCP */
sockid = socket( AF_INET,SOCK_STREAM,0);
/*initializes server port variable, htons converts 2034 to network byte order
as can be done with the server IP address*/
serv_addr.sin_port = htons("11000");
/*Sets address for socket to bind to (0.0.0.0 probably)*/
serv_addr.sin_addr.s_addr = INADDR_ANY;
/*Tells system to use the IPv4 address family*/
serv_addr.sin_family = AF_INET;
/*Binds socket to the address and port specified earlier*/
n = bind(sockid, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
/*Listen on created and binded socket, allow for a 5 connection queue*/
z = listen(sockid, 5);
/*Gets the length of the address*/
clilen = sizeof(cli_addr);
if ( n < 0){
printf("ERROR NO: %d\n",errno);
}
/*accept connection request creating new socket for that connection
unless specifically set otherwise the accept() function will stop all commands
until a connection is requested*/
newsockid = accept(sockid, (struct sockaddr *) &cli_addr, &clilen);
//Set the 256byte buffer to zero
bzero(buffer,256);
/*read() will stop all commands until it is sent something to read,
the it will put any status numbers is n, the newsockid from the
accept() function is used, and all input is put into the buffer.
only 255 or less bytes can be put into the read buffer this way.*/
while (0==0){
n = read(newsockid,buffer,255);
n = write(newsockid,"hello there",11);
}
return(0);
}


