I have been reading Unix Network Programming by Stevens, and have made a small client/server pair to test the fork() function and become famililar with such. I have made previous client/server pairs that work, but for some reason I can't get this one to complete a connecting. The server just sits there listening even after the client has sent a SYN. Here are the main functions for both.
server main()
Code:
int main(int argc, char *argv[])
{
int listenfd, connfd;
pid_t childp;
socklen_t clientlen;
struct sockaddr_in server, client;
if (argc != 2) {
printf("USAGE: <port>\n");
exit(1);
}
/* create initial socket */
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
/* set socket info */
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(atoi(argv[1]));
/* binds */
Bind(listenfd, (struct sockaddr *) &server, sizeof(server));
/* and listen */
Listen(listenfd, 5);
printf("Listening on port %d...\n", atoi(argv[1]));
/* signal handler */
signal(SIGCHLD, sig_chld);
/* child process loop */
for ( ; ; ) {
clientlen = sizeof(client);
printf("!");
if ((connfd = accept(listenfd, (struct sockaddr *) &client, &clientlen)) < 0) {
if (errno == EINTR)
continue;
else
perror("accept error");
}
if ((childp = fork()) == 0) { /* child process */
close(listenfd);
str_echo(connfd);
exit(0);
} else if (childp == -1)
perror("fork");
close(connfd);
}
}
client main()
Code:
main(int argc, char *argv[])
{
int i, sockfd;
struct sockaddr_in server;
if (argc != 3) {
printf("USAGE: <ip address> <port> <# of connections>\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
memset(&server, '\0', sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(atoi(argv[2]));
server.sin_addr.s_addr = inet_aton(argv[1]);
printf("Attempting connection to %s\n",argv[1]);
if (connect(sockfd, (struct sockaddr *) &server, sizeof(server)) == -1) {
perror("connect");
exit(1);
}
str_cli(stdin, sockfd);
exit(0);
}
Any help would be greatly appreciated. It's probably something small that I have been staring at for hours and haven't been able to pickup.
EDIT: Well I found the problem:
server.sin_addr.s_addr = inet_aton(argv[1]);
this for some reason is setting an incorrect IP address. I was told to try inet_pton instead, which I am going to do now, but I am still curious why when argv[1] is "127.0.0.1" after fetching and printing the value for server.sin_addr.s_addr I get 1.0.0.0
EDIT AGAIN: Well after using inet_pton everything works, but I am still stumped as to why inet_aton didn't work. I used it in the exact same way in a pervious app with no problems. Feel free to deliver any insight on the issue.