Hi, I'm learning network programming from Beej tutorial.
I changed his server examole to work under Windows. Here's the code:
When I execute this code and in Start\Run type:
telnet hostname 3490 I get message Hello world and after that Connection to host lost. At the same time in first window (server) I see infinte loop with text: "accept: No error", I assume it is perror("accept"). Now, when I try once more to start telnet I get message:
Could not open connection to the host, on port 3490. No connection could be made because the target machine actively refused it.
I don't think this program is supposed to do this. If someone can explain me why it is happenning and how to fix it.
Thanks
I changed his server examole to work under Windows. Here's the code:
Code:
#include <winsock.h>
#include <stdio.h>
#define MYPORT 3490
#define BACKLOG 10
int main(void)
{
WSADATA wsaData;
SOCKET sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
int yes=1;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
fprintf(stderr, "WSAStartup failed.\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char*)&yes,sizeof(yes)) == -1) {
perror("setsockopt");
exit(1);
}
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);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))
== -1) {
perror("bind");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror("listen");
exit(1);
}
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr,
&sin_size)) == -1) {
perror("accept");
continue;
}
printf("server: got connection from %s\n",
inet_ntoa(their_addr.sin_addr));
closesocket(sockfd);
if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
perror("send");
closesocket(new_fd);
}
return 0;
}
When I execute this code and in Start\Run type:
telnet hostname 3490 I get message Hello world and after that Connection to host lost. At the same time in first window (server) I see infinte loop with text: "accept: No error", I assume it is perror("accept"). Now, when I try once more to start telnet I get message:
Could not open connection to the host, on port 3490. No connection could be made because the target machine actively refused it.
I don't think this program is supposed to do this. If someone can explain me why it is happenning and how to fix it.
Thanks