I wrote a simple program that reads input from stdinand sends it over TCP to a server listening on port 15557.
When I compile and run it under Linux, it works fine. However, when I try to compile and run it under Cygwin, it crashes with the following error message:
$ ./a.out servername.net 15557 < test.dat
Unable to connect: Cannot assign requested address
I eliminated any problems with the firewall / network, as I can connect via telnet to the same server and send the same data entered manually.
Any idea what is going wrong here?
UPDATE
Following the prompt of @Hasturkun, I started a program under GDB to verify that the result gethostbyname. Here it is right after the call gethostbyname:
(gdb) print *serverent
$2 = {h_name = 0x603217 "bilbo.neurobat.net", h_aliases = 0x603030, h_addrtype = 2, h_length = 4, h_addr_list = 0x6031c0}
(gdb) print serverent->h_addr_list[0]
$3 = 0x60322c ">\002V0"
(gdb) print atoi(">\002V0")
$5 = 0
, " > \002V0". , -?
/UPDATE
FWIW, :
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include "neurocli.h"
int main(int argc, char* argv[]) {
char *line = NULL;
char buf[40] = {0};
ssize_t write_len = 0, read_len;
size_t n = 0;
int neuro_socket;
if (argc != 3) {
fprintf(stderr, "Usage: %s host port\n", argv[0]);
return -1;
}
neuro_socket = open_tcp_socket(argv[1], atoi(argv[2]));
while ((write_len=getline(&line, &n, stdin)) != -1) {
printf("# %s", line);
if (write(neuro_socket, line, write_len) < 0) {
perror("Unable to write to server");
exit(EXIT_FAILURE);
}
if (*line=='\n') {
read_len = read(neuro_socket, buf, 40);
buf[read_len] = '\0';
printf("%s", buf);
close(neuro_socket);
neuro_socket = open_tcp_socket(argv[1], atoi(argv[2]));
}
free(line);
line = NULL;
}
free(line);
close(neuro_socket);
return 0;
}
int open_tcp_socket(char *server, int port) {
int result;
static struct sockaddr_in *sockaddr;
if ((result = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("Unable to create socket");
exit(EXIT_FAILURE);
}
if (sockaddr==NULL)
sockaddr = make_sockaddr(server, port);
if (connect(result, (struct sockaddr*)sockaddr, sizeof(*sockaddr)) != 0) {
perror("Unable to connect");
exit(EXIT_FAILURE);
}
return result;
}
struct sockaddr_in *make_sockaddr(char *name, int port) {
struct sockaddr_in *sockaddr = malloc(sizeof(struct sockaddr_in));
struct hostent *serverent;
memset(sockaddr, 0, sizeof(*sockaddr));
sockaddr->sin_family = AF_INET;
sockaddr->sin_port = htons(port);
if ((serverent = gethostbyname(name)) == NULL) {
perror("Unable to lookup server IP address");
exit(EXIT_FAILURE);
}
sockaddr->sin_addr.s_addr = atoi(serverent->h_addr_list[0]);
return sockaddr;
}