Reputation: 6691
I am new to unix socket programming. I haven't found myself a comfortable book or tutorial and so I am really struggling.
Here is the program code:
#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include <netinet/in.h>
int main(){
printf("one");
int socketHandle, newSocketHandle, portno;
struct sockaddr_in serverAddress, clientAddress;
printf("two");
portno = 5001;
bzero((char *) &serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(portno);
printf("three");
//creating the socket
socketHandle = socket(AF_INET, SOCK_STREAM, 0);
if(socketHandle < 0){
perror("ERROR : Socket not created.");
return -1;
}
printf("Socket created.");
//binding the socket
if(bind(socketHandle, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0){
perror("ERROR : Socket not binded.");
return -1;
}
printf("Socket binded.");
//make the socket listen
listen(socketHandle, 5);
int len = sizeof(clientAddress);
//accept the connection requests
newSocketHandle = accept(socketHandle, (struct sockaddr *) &clientAddress, &len);
if(newSocketHandle < 0){
perror("ERROR : Connection not accepted.");
}
printf("Connection accepted.");
return 0;
}
(I tried to print one
, two
, and three
for debugging)
But, even the printf("one")
in the first line doesn't work. The cursor just keeps blinking (indicating that the program is still in execution). I can't even get a clue of what is going wrong in the above program. Using the bzero()
function also throws a warning saying
warning: incompatible implicit declaration of built-in function ‘bzero’ [enabled by default]
I find socket programming difficult as different websites show different code. Also, please suggest any good tutorial on C/C++ socket programming.
Upvotes: 2
Views: 3766
Reputation: 2066
Make sure to print a newline in your debug messages for them to show immediately.
Example printf("one\n");
If you really don't want newlines you can instead flush output with fflush(stdout);
.
Upvotes: 6
Reputation: 817
It is better to use the Beej's guide to network programming as a starting point and use it's sample codes : http://beej.us/guide/bgnet/output/print/bgnet_USLetter.pdf
Upvotes: 3