This is the code of my server:
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
int main (int argc, char **argv)
//------------------------MAIN--------------------------//
{
int sock; // sock descriptor
int new_sock;
int c;
int sin_size;
int koniec = 0;
char *ip_address;
char *port_number;
while (1)
{
static struct option OpcjeProgramu[] =
{
{ "port", required_argument, 0, 'p'},
{ "interface", required_argument, 0, 'i'},
{ 0, 0,0,0 }
};
int option_index = 0;
c = getopt_long (argc, argv, "p:i:", OpcjeProgramu, &option_index);
if ( c == -1 )
break;
switch(c)
{
case 0:
if (OpcjeProgramu[option_index].flag != 0)
break;
printf ("Option $s", OpcjeProgramu[option_index].name);
if (optarg)
printf (" with argument %s", optarg);
printf ("\n");
break;
case 'p':
printf ("Port number: %s\n",optarg);
port_number = strdup(optarg);
//snprintf(port_number,ROZMIAR,"%s",optarg);
break;
case 'i':
printf ("IP address: %s\n",optarg);
ip_address = strdup(optarg);
break;
case '?':
puts(" This program invoke with -p (--port), -i(interface).");
puts(" \n Example: \n topserver -1 127.0.0.1 --port=10001");
// getopt_long wyswietli informacje o bledzie
break;
default:
abort();
}
}
printf(" ip_address: %s\n",ip_address);
printf(" port_number: %s\n", port_number);
int port_nr;
port_nr = atoi(port_number);
struct sockaddr_in serveraddr; // information about server
struct sockaddr_in clientaddr; // information about client
memset(&serveraddr, 0, sizeof(struct sockaddr_in));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons((u_short) port_nr);
serveraddr.sin_addr.s_addr = htonl(inet_addr(ip_address));
// Set up sock:
if( ( sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP) ) < 0 )
{
perror("Nie mozna utworzyc gniazdza");
return 1;
}
printf("Sock is set up, handle=%d\n", sock);
if(bind(sock,(struct sockaddr*) &serveraddr, sizeof(serveraddr) < 0))
{
perror(" Error.");
close(sock);
return 1;
}
puts("Sock is bound.\n");
puts("listen...\n");
listen(sock, 32767);
Unfortunately, when I run the program for example ./server -p 1234 - i 127.0.0.1
The program returns:
Sock is set up, handle =3
Error: Invalid argument
Why does my bind function not work?
In this program I have to invoke my program with options, so I'm using the getopt()
library.