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)
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 )

        case 0:
        if (OpcjeProgramu[option_index].flag != 0)
        printf ("Option $s", OpcjeProgramu[option_index].name);
               if (optarg)
                printf (" with argument %s", optarg);
                printf ("\n");


        case 'p':
        printf ("Port number: %s\n",optarg);
        port_number = strdup(optarg);


        case 'i':
        printf ("IP address: %s\n",optarg);
        ip_address = strdup(optarg);

        case '?':
        puts(" This program invoke with -p (--port), -i(interface).");
        puts(" \n Example: \n  topserver -1 --port=10001");
// getopt_long wyswietli informacje o bledzie


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.");
        return 1;

puts("Sock is bound.\n");


listen(sock, 32767);

Unfortunately, when I run the program for example ./server -p 1234 - i

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.

Accepted Answer

You misplaced the less-than sign. It should read:

if (bind(sock,(struct sockaddr*) &serveraddr, sizeof(serveraddr)) < 0)
Written by interjay
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki