Hi. I recently started learning network programming (from Beej's guide); here's a simple server I'm trying to make - its supposed to send a file to a specified port (both file_path and port number are provided from the terminal. I am getting a warning "server.c:78: warning: ‘client_address’ may be used uninitialized in this function" though it compiles. When I try to run it I get an error with bind(), but I'm not sure what's wrong with it.
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
/*Return in case of insufficient input*/
if(argc!=3)
{
fprintf(stderr,"Usage: server path_to_file port_number");
return 1;
}
struct addrinfo hints,*res;
memset(&hints,0,sizeof(hints));
/*Setup hints for getaddrinfo*/
hints.ai_family=AF_UNSPEC;
hints.ai_flags=AI_PASSIVE;
hints.ai_socktype=SOCK_STREAM;
int status;
status=getaddrinfo(NULL,argv[2],&hints,&res);
if(status!=0)
{
fprintf(stderr,"Error with getaddrinfo");
return 2;
}
int fd=socket(res->ai_family,res->ai_socktype,res->ai_protocol);
assert(fd!=-1);
/*Something wrong here?*/
status=bind(fd,res->ai_addr,res->ai_addrlen);
if(status!=0)
{
fprintf(stderr,"Error with bind");
return 3;
}
/*Listen for incoming connections*/
status=listen(fd,10);
if(status!=0)
{
fprintf(stderr,"Error with listen");
return 4;
}
/*accept*/
struct sockaddr *client_address;
socklen_t *client_addrlen;
int new_fd=accept(fd,client_address,client_addrlen);
assert(new_fd!=-1);
/*Open file that is to be sent*/
FILE *file_to_send=fopen(argv[1],"r");
assert(file_to_send!=NULL);
/*Buffer for storing bytes*/
void *buff=malloc(500);
fread(buff,1,250,file_to_send);
send(new_fd,buff,250,0);
freeaddrinfo(res);
fclose(file_to_send);
return 0;
}
Thank you.