whats wrong with this simple code?

R

Robert Smith

Why doesnt this code work???? it just stops at the socket() and does not
print HI.
why is this?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define MYPORT 3490

int main()
{
int socket_id, newsocket;
int listen_return;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;

socket_id =socket(AF_INET, SOCK_STREAM, 0); <--------- here god
damn it
printf("HI");
my_addr.sin_family = AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
memset(&(my_addr.sin_zero), '\0',8);

bind(socket_id, (struct sockaddr *)&my_addr,sizeof(struct sockaddr));

while(0==0)
{

if(listen(socket_id, 10)==0)
{
printf("Connected");
newsocket=accept(socket_id, (struct sockaddr*)&their_addr,
sizeof(struct sockaddr_in));

}
else
{
printf("not connected");
}

};

return 0;
}
 
A

Andre Kostur

Why doesnt this code work???? it just stops at the socket() and does
not print HI.
why is this?

Um... there's nothing C++-specific in here... it's all stock C. (OK,
ignoring that all the BSD stuff isn't Standard....)

Anyway, your problem is most likely the buffered output of printf. You
might want to try sticking "\n" at the end of your printf string
literals.
#include <stdio.h>

Deprecated said:
#include <stdlib.h>

Deprecated said:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

All non-standard....
#define MYPORT 3490

int main()

Good for you... someone who does use a Standard main() :)
{
int socket_id, newsocket;
int listen_return;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;

socket_id =socket(AF_INET, SOCK_STREAM, 0); <--------- here
god
damn it
printf("HI");
my_addr.sin_family = AF_INET;
my_addr.sin_port=htons(MYPORT);
my_addr.sin_addr.s_addr=INADDR_ANY;
memset(&(my_addr.sin_zero), '\0',8);

bind(socket_id, (struct sockaddr *)&my_addr,sizeof(struct
sockaddr));

You might want to check the return value of bind.... you may not be able
to get the port....
while(0==0)

What's wrong with "while(true)". IMHO: it's clearer... I briefly
thought: "while false? huh? Oh wait, he's comparing 0 to 0.. that's
while true."
{

if(listen(socket_id, 10)==0)

Your program is probably getting to this listen statement, and then
blocks until it gets a connection. But since none of the printfs caused
the buffer to be flushed, you probably aren't getting any output....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top