socket programming

Post questions regarding programming in C/C++ in Linux/Unix.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

socket programming

Postby nickbird » Fri Sep 02, 2005 8:08 pm

I followed beej's guide on this one but made it all pretty and added classes, but I can't get the damnable thing to bind...

CSocket.h
Code: Select all
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <iostream>
#define BACKLOG 10

using namespace std;

class CSocketServer {
   private:
      int sockfd;
      int new_fd;
      struct sockaddr_in my_addr;
      struct sockaddr_in their_addr;
      socklen_t sin_size;
      struct sigaction sa;
      int yes;
   public:
      CSocketServer(int port);
};

CSocketServer::CSocketServer(int port)
{
   int yes=1;
   my_addr.sin_family = AF_INET;
   my_addr.sin_port = htons(1004);
   my_addr.sin_addr.s_addr = INADDR_ANY;
   memset(&(my_addr.sin_zero), '\0', 8);
   
   if(bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1)
   {
      cout << "[Error in bind]\n";
      exit(1);
   }
   
   if(listen(sockfd, BACKLOG) == -1)
   {
      cout << "[Error in listen]\n";
      exit(1);
   }

   while(1)
   {
      sin_size = sizeof(struct sockaddr_in);
      if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,
           &sin_size)) == -1)
      {
         cout << "[Error in accept]\n";
         exit(1);
      }
      cout << "Server: got connection from " << inet_ntoa(their_addr.sin_addr) << endl;
      if(!fork())
      {
         close(sockfd);
         if(send(new_fd, "Hello, world!\n", 14,0) == -1)
         {
            cout << "[Error in send]\n";
            exit(1);
         }
         close(new_fd);
         exit(0);
      }
         close(new_fd);
   }
      exit(0);
}
   


sockettest.cpp
Code: Select all
#include "CSocket.h"

int main(int argc, char** argv)
{
   CSocketServer s(1004);
   return 0;
}



any ideas?

thanks
-nickbird
nickbird
 
Posts: 4
Joined: Tue Mar 22, 2005 4:42 pm

Postby devil_slayer » Sat Sep 03, 2005 7:00 am

Read the tutorials again. You first need to create a socket like so:
Code: Select all
sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
        if(sockfd<0)
        {
                error="Error creating server socket!";
                return -1;
        }
User avatar
devil_slayer
 
Posts: 489
Joined: Wed Oct 01, 2003 3:44 am
Location: Warsaw, POLAND


Return to Unix/Linux

Who is online

Users browsing this forum: No registered users and 2 guests