Reputation: 3824
I've read many examples on networking with C and I'm stuck. I can see that the TCP packets with the SYN flag are on the wire (with wireshark), but the receiving end (I've set up a virtual machine for testing purposes) sends nothing back, not even RST.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <strings.h>
int establish_tcp(int port) {
char *ip = "10.0.2.15"; /* Virtual Machine */
struct sockaddr_in sockaddrin;
struct hostent *host;
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
fprintf(stderr, "Socket Error\n");
exit(1);
}
sockaddrin.sin_family = AF_INET;
host = gethostbyname(ip);
if(host == NULL) {
fprintf(stderr, "%s unknown host.\n", ip);
exit(2);
}
/* copies the internet address into the struct */
bcopy(host->h_addr, &sockaddrin.sin_addr, host->h_length);
/* specify port (used by TCP a layer above */
sockaddrin.sin_port = port;
/* try to connect */
return connect(sock, (struct sockaddr*) &sockaddrin, sizeof(struct sockaddr_in));
}
int main(void) {
printf("status: %i\n", establish_tcp(80));
return 0;
}
It takes a while until the packets are timed out and -1 is returned as status code. How can it happen that the target machine doesn't send a reply? What have I overlooked?
I think I've figured out that it is not a setup problem. I'm running Ubuntu 12.04. The virtual machine is a Debian Wheezy, I check its IP with ifconfig
. I tried if the machine is reachable with telnet
.
To escape issues which might be related to Virtual Box I tried to replace the IP with the one of Google, yielding the same results.
Upvotes: 1
Views: 6058
Reputation: 409442
The problem most likely is this:
sockaddrin.sin_port = port;
The port number has to be in network byte order, which is different from the native byte order in x86 and x86_64 machines.
Change to:
sockaddrin.sin_port = htons(port);
Upvotes: 4