Client Server problem with connect() or accept()
all. I'm having a bit of weird problem with client server program. I have two different kinds of clients trying to connect to one server, one is just more barebone than the other with less things to do. But other wise they are practically the same. While the barebone code can connect to server and server accepts it fine, the elaborate version of it can't. The client says it's connected, sends messages (via both send() and sendto()) and gets number of bytes sent back. But the server doesn't recognize it. I'm not really sure why, esp upon comparing both versions of clients, they are really the same thing (at least until connect() is called), elaborate version has bind() whereas barebone version doesn't. Can anybody see a problem as to why these very similar codes don't work similar :P
if (argc == 3)
{
host = argv[1]; // server address
info.c_name = argv[2];
}
else
{
printf("plz read the manual, kthxbai\n");
exit(1);
}
hp = gethostbyname(host);
if (!hp)
exit(1);
printf("host found\n");
// setting up address and port structure information
bzero((char * ) &server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(SERVER_PORT);
// opening up socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
exit(1);
else
printf("socket is opened: %i \n", sockfd);
info.sock_fd = sockfd;
// binding socket to a port: not in barebone version
rv = bind(sockfd, (struct sockaddr *) &server_address, sizeof(server_address));
if (rv < 0)
{
printf("MAIN: ERROR bind() %s\n", strerror(errno));
exit(1);
}
else
printf("socket is bound\n");
// connecting
rv = connect(sockfd, (struct sockaddr *) &开发者_如何学Pythonserver_address, sizeof(server_address));
printf("rv = %i\n", rv);
if (rv < 0)
{
printf("MAIN: ERROR connect() %i: %s\n", errno, strerror(errno));
exit(1);
}
else
printf("connected\n");
I'm not even sure where the problem is, whether it's the elaborate version of client or it's just the server? Thanks for any enlightenment.
If the code is really what you're using, your client is (magically!) connecting to itself, due to TCP's somewhat obscure Simultaneous connect support.
The problem here is that you aren't using the return for gethostbyname
at all.
You also shouldn't bind the server port if it might be running on the local machine.
精彩评论