Question

When I run the code it doesn't seem to run the entire main function when this line

connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); 

is in it. It won't even print the first cout at the beginning, but when I comment it out it works fine,can someone tell me the reason for this?

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <iostream>

#define PORT 1227
#define SIM_LENGTH 10;
using namespace std;
void clean_up(int cond, int *sock){
cout<<"exiting";
close(*sock);
exit(cond);
}

int main(void){
cout<<"working;
int sock;
int connect_sock;
struct sockaddr_in serv_name;
size_t len;
int count;

sock =  socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
cout<<"Error connecting to socket";
clean_up(1, &sock);
}
bzero(&serv_name, sizeof(serv_name)); // set name as physical address
serv_name.sin_family = AF_INET;
serv_name.sin_port = htons(PORT);
if(bind(sock,(struct sockaddr *)&serv_name, sizeof(serv_name))<0){
cout<<"error naming channel";
clean_up(1, &sock);
}
cout<<"waiting for connection from client";
listen(sock, 1);
len = sizeof(serv_name);
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len);
cout<<connect_sock;
cout<<"server wrote";
close(connect_sock);
cout<<"connect?";
}
Was it helpful?

Solution

It's waiting for a connection. It doesn't print the first cout because you didn't ask it to. Try:

cout<<"waiting for connection from client"<<endl;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top