Search code examples
c++socketsnetwork-programmingtcp

Simple Server Socket stucks at bind


im trying to write a simple Server/Client program in c++ on Linux(Ubuntu). But now i got an Problem at my server code. I could compile the code, but when i run it, it gets stuck every time at the bind function. But i get no error message. It even runs for several minutes and i don't get any feedback. Do you guys have any idea why it is not working?

thanks for your help.

#include<string.h>
#include<unistd.h>
#include<sys/types.h> 
#include<sys/socket.h>
#include<netinet/in.h>
#include<iostream>

int main()
{
   int sockfd, newsockfd, portno;
   socklen_t clilen;
   char buffer[256];
   struct sockaddr_in serv_addr, cli_addr;
   int n;

   std::cout << "Creating socket..\n";
   sockfd = socket(AF_INET, SOCK_STREAM, 0);

   memset(&serv_addr, 0, sizeof(serv_addr));
   portno = atoi("5001");

   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = INADDR_ANY;
   serv_addr.sin_port = htons(portno);

   std::cout << "Binding socket..\n";

   int enable = 1;
   if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
      std::cout << "setsockopt(SO_REUSEADDR) failed\n";

   if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) 
      std::cout << "ERROR on binding\n";

   std::cout << "Listening..";
   listen(sockfd,5);

   clilen = sizeof(cli_addr);
   newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
   if (newsockfd < 0) 
      std::cout << "ERROR on accept\n";

   bzero(buffer,256);
   n = read(newsockfd,buffer,255);

   n = write(newsockfd,"I got your message",18);

   close(newsockfd);
   close(sockfd);
   return 0; 
}

Im using this command to compile: c++ server.cpp -o server

To run it i use: ./server


Solution

  • replace std::cout << "Listening.."; with std::cout << "Listening.." << std:flush; and read How does std::flush work? for your future projects

    Basically your server was already listening for new connections, but you were missing the "Listening.." output on your console, weren't you?