I had used Windows for socket programming recently, but my assignment requires students to use Linux Socket header(sys/socket.h) rather than Windows one. So I'm starting from ground zero but the program freezes even though it is a very simple program that does nothing but only prints a message when a connection is made.
Server.cpp
#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
#define BACKLOG 10
int main(void){
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
socklen_t sin_size;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){
perror("Socket creation failed");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr))==-1){
perror("Socket binding failed");
exit(1);
}
if(listen(sockfd, BACKLOG) == -1){
perror("Socket listening failed");
exit(1);
}
sin_size = (socklen_t)sizeof(struct sockaddr_in);
while(true){
printf("Loop Test"); // This is not displayed at all
if((new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size))==-1){
perror("Connetion accepting failed");
exit(1);
}
printf("Server got connection from %s\n", inet_ntoa(their_addr.sin_addr));
}
return 0;
}
Client.cpp
#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
int main(void){
int sockfd;
struct sockaddr_in their_addr;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
perror("Socket generating failed");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT);
their_addr.sin_addr.s_addr = INADDR_LOOPBACK;
if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) == -1){
perror("Connection failed");
exit(1);
}
printf("Loop test"); // This is not displayed no matter if server is on or not
return 0;
}
As I mentioned in the code, it just stops and both perror and printf(for debugging) are not displayed. Why is this happened? (I'm using Ubuntu)